如何理解这个找到最长单词的代码

时间:2014-12-29 03:18:32

标签: ruby

我目前正在学习" Ruby语言"我被困在" enumerable"我很难理解它,但仍然是一个例子。

my_array = %w{this is a test of the longest word check} 
longest_word = ''

my_array.each do |word|
  longest_word = word if longest_word.length < word.length
end

puts longest_word
#=> longest

除了longest_word = word if longest_word.length < word.length之外,我几乎可以理解每一行。我想这也是这个程序的主要部分。如何通过这样的比较得到想要的结果呢?

起初我认为longest_word是默认方法,但显然不是这样。然后我将它引用到&#34;可枚举的&#34;这是否意味着当每个迭代器迭代从最短到最长的单词时,是我们如何得到想要的结果,希望有人可以帮助我更深入和清楚地理解这一点。

3 个答案:

答案 0 :(得分:3)

longest_word = word if longest_word.length < word.length是一种写作的简写方式:

if longest_word.length < word.length
    longest_word = word
end

以下是代码的注释版本:

# Define an array of words to test
my_array = %w{this is a test of the longest word check}

# Set our initial longest word to be a blank string so that any word will be longer than this 
longest_word = ''

# loop through the array testing each word in the order it was put into the array
my_array.each do |word|
  # if this word is longer than the longest word we have found so far, store it as the longest word
  longest_word = word if longest_word.length < word.length
end

# output the longest word
puts longest_word

答案 1 :(得分:3)

仅供参考,如果您想找到最长的单词,那么您也可以尝试sort_by ..

2.1.5 :001 >   my_array = %w{this is a test of the longest word check} 
 => ["this", "is", "a", "test", "of", "the", "longest", "word", "check"]
2.1.5 :002 > my_array.sort_by(&:length).last
 => "longest"  # will return longest word from the string array

为什么.last方法?

2.1.5 :003 > my_array.sort_by(&:length)
 => ["a", "of", "is", "the", "this", "test", "word", "check", "longest"]

将按照我们想要的最长字按升序对数组进行排序,使其位于最后index

<强>更新@engineersmnky所述,您还可以使用更短的方法:max_by。让我们看看它是如何工作的:

 >  my_array = %w{this is a test of the longest word check} 
 => ["this", "is", "a", "test", "of", "the", "longest", "word", "check"] 
 > my_array.max_by(&:length)
 => "longest"

答案 2 :(得分:2)

还有更多的替代词来获得最大的词 -

2.1.5 :001 > my_array = %w{this is a test of the longest largest word check}
=> ["this", "is", "a", "test", "of", "the", "longest", "largest", "word", "check"]
2.1.5 :001 > my_array.max {|a,b| a.length <=> b.length }
=> "longest"

2.1.5 :001 > my_array.max_by {|x| x.length }
=> "longest"