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

ruby – 重要的是什么目的?第7行

发布时间:2020-12-17 01:49:22 所属栏目:百科 来源:网络整理
导读:我想知道计数变量的用途是什么,就在最后一个结束之前? # Pick axe page 51,chapter 4# Count frequency methoddef count_frequency(word_list) counts = Hash.new(0) for word in word_list counts[word] += 1 end counts #what does this variable actuall
我想知道计数变量的用途是什么,就在最后一个结束之前?

# Pick axe page 51,chapter 4

# Count frequency method
def count_frequency(word_list)
    counts = Hash.new(0)
    for word in word_list
        counts[word] += 1
    end
    counts    #what does this variable actually do?
end

puts count_frequency(["sparky","the","cat","sat","on","mat"])

解决方法

任何Ruby方法中的最后一个表达式是该方法的返回值.如果计数不在方法的末尾,则返回值将是for循环的结果;在这种情况下,这是word_list数组本身:

irb(main):001:0> def count(words)
irb(main):002:1>   counts = Hash.new(0)
irb(main):003:1>   for word in words
irb(main):004:2>     counts[word] += 1
irb(main):005:2>   end
irb(main):006:1> end
#=> nil
irb(main):007:0> count %w[ sparky the cat sat on the mat ]
#=> ["sparky","mat"]

有人可能在1.9中编写相同方法的另一种方式:

def count_frequency(word_list)
  Hash.new(0).tap do |counts|
    word_list.each{ |word| counts[word]+=1 }
  end
end

虽然有些人认为像这样使用tap是一种滥用行为.

(编辑:李大同)

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

    推荐文章
      热点阅读