Is it acceptable having parameter in class constructor?

后端 未结 3 1028
感情败类
感情败类 2021-01-13 06:33

a rubygem I\'m writing and that is useful for counting word occurrences in a text, I choose to put 3 parameters in class constructor.

The code is working, but I want

3条回答
  •  离开以前
    2021-01-13 07:14

    You could do it the rails way, where options are given in a hash:

    def initialize(filename = nil, options = {})
      @hide_list = options[:hide_list]
      @words = options[:words]
    
      if filename
        @filename = filename
        @occurrences = read
      else
        @filename = STDIN
        @occurrences = feed
      end
    
      @sorted = Array(occurrences).sort { |one, two| -(one[1] <=> two[1]) }
    
    end
    

    Then you can call it like this:

    WC.new "file.txt", :hide_list => %w(a the to), :words => %w(some words here)
    

    or this:

    wc = WC.new
    wc.hide_list = %w(a the is)
    wc.words = %w(some words here)
    

提交回复
热议问题