I am a beginner at Ruby and have been having some trouble figuring out why I can't modify an initialized variable placed outside a block. For example, I want to do the following (but without a for loop because I heard using it in Ruby can cause some nasty bugs):
sentence = "short longest"
def longest_word(sentence)
max_length = 0
for word in sentence.split(" ")
if word.length > max_length
max_length = word.length
max_word = word
end
end
return max_word
end
What I tried:
def longest_word(sentence)
max_length = 0
sentence.split(" ").each do |word|
if word.length > max_length
max_length = word.length
max_word = word
end
end
return max_word
end
I understand that you can use something like this:
def longest_word(sentence)
return sentence.split(" ").each.map {|word| [word.length, word]}.max[1]
end
as well but just wanted to figure out why I can't do the .each method in the same way I can do the for loop method. Any help would be appreciated!
max_lengthvariable, that is. You just forgot to initializemax_wordoutside as well.