加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 在类构造函数中有参数是否可以接受?

发布时间:2020-12-17 03:19:01 所属栏目:百科 来源:网络整理
导读:我正在写一个 rubygem,它对于计算文本中的单词出现很有用,我选择在类构造函数中放入3个参数. 代码正在运行,但我想重构它以获得好处. 根据您的经验,使用没有参数和许多setter / getters方法或类似代码的构造函数来读取/保留/使用API??作为API更容易,构造函数
我正在写一个 rubygem,它对于计算文本中的单词出现很有用,我选择在类构造函数中放入3个参数.

代码正在运行,但我想重构它以获得好处.
根据您的经验,使用没有参数和许多setter / getters方法或类似代码的构造函数来读取/保留/使用API??作为API更容易,构造函数中包含所有参数?

TIA

保罗

def initialize(filename,words,hide_list)

  if ! filename.nil?
    @filename = filename
    @occurrences = read
  else
    @filename = STDIN
    @occurrences = feed
  end

  @hide_list = hide_list
  @sorted = Array(occurrences).sort { |one,two| -(one[1] <=> two[1]) }
  @words = words

end

解决方法

您可以通过rails方式执行此操作,其中选项以散列形式给出:

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

然后你可以像这样调用它:

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

或这个:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读