ruby – 在类构造函数中有参数是否可以接受?
发布时间:2020-12-17 03:19:01 所属栏目:百科 来源:网络整理
导读:我正在写一个 rubygem,它对于计算文本中的单词出现很有用,我选择在类构造函数中放入3个参数. 代码正在运行,但我想重构它以获得好处. 根据您的经验,使用没有参数和许多setter / getters方法或类似代码的构造函数来读取/保留/使用API??作为API更容易,构造函数
我正在写一个
rubygem,它对于计算文本中的单词出现很有用,我选择在类构造函数中放入3个参数.
代码正在运行,但我想重构它以获得好处. 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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- xcode – 调用shadowCastBitMask =时屏幕大小调整
- ruby-on-rails – rails 3将html标签打印到屏幕而
- Oracle断电恢复ORA-00600: 内部错误代码, 参数:
- c# – Stackoverflow API响应格式
- 聊聊 Swift 3.0 - 新版本对我们的影响
- c# – XAML中的触发器
- ajax – 如何在django中的preflighted CORS POST
- 在Flex控件中使用XMLListCollection
- c# – 如何通过.NET验证xml代码文件?如果我使用
- nagios报 check_oracle_rman_backup_problems告警
热点阅读