Noob question - simple "find longest word in string" problem

Hi, i just started learning ruby. Can someone please explain to me why
the following code returns “false”? I dont get it. The goal here was to
create a def that would print the longest word of the sentence. So it
does “puts” (line 5) the longest word (in this case “abcdefg”) but when
i do a boolean to check if thats true, i get a “false” in return.

def longest_word(sentence)

array1 = sentence.split(" ")
array2 = array1.sort {|word| word.length}
puts array2[0]

end

puts (longest_word(‘abc abcdefg’) == ‘abcdefg’).to_s

thanks for the help

Evert Rotshy wrote in post #1169997:

array2 = array1.sort {|word| word.length}
puts array2[0]

you sort by word size, so first word is the smaller

try

def findl(str)
(str||"").scan(/[\w\d]+/).
sort_by {|a| -a.size}.
first || “”
end

There are, of course, more arcane ways of doing this:

irb(main):012:0> “fo bar nbasduzuas car”.scan(/\w+/).max_by {|w|
w.length}
=> “nbasduzuas”

or even

irb(main):014:0> “fo bar nbasduzuas car”.scan(/\w+/).max_by(&:length)
=> “nbasduzuas”

:slight_smile:

assuming that words are delimited by whitespace alone

longest_word = “what is the longest word in this string?”.split.sort
{|word| word.length}.last

Evert Rotshy wrote in post #1169997:

Hi, i just started learning ruby. Can someone please explain to me why
the following code returns “false”? I dont get it. The goal here was to
create a def that would print the longest word of the sentence. So it
does “puts” (line 5) the longest word (in this case “abcdefg”) but when
i do a boolean to check if thats true, i get a “false” in return.

def longest_word(sentence)

array1 = sentence.split(" ")
array2 = array1.sort {|word| word.length}
puts array2[0]

end

puts (longest_word(‘abc abcdefg’) == ‘abcdefg’).to_s

thanks for the help

Look at these examples.

You are doing this.

def adder1(a,b)
puts a+b
end

p adder1(2,3)
puts (adder1(2,3) == 5)

puts
puts

######## Try this instead.

def adder2(a,b)
a+b
end

p adder2(2,3)
puts (adder2(2,3) == 5)

Harry

Online Karnaugh map solver with circuit
http://www.32x8.com

def longest_word(sentence)

array1 = sentence.split(" ")
array2 = array1.sort {|word| word.length}
puts array2[0]

end

a =[“a”,“ab”,“abc”,“b”,“bcd”,“test”,“r”,“def”]
p a
puts

p a.sort{|word| word.length}
#> [“def”, “bcd”, “a”, “test”, “abc”, “r”, “ab”, “b”]

p a.sort{|x,y| x.length <=> y.length}
#> [“a”, “b”, “r”, “ab”, “bcd”, “def”, “abc”, “test”]

Harry

Online Karnaugh map solver with circuit
http://www.32x8.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs