Loops

B

Bruce Wayner

Hi, I'm only a newbie on ruby could someone help me with my code:
Here's: I'm writing a program which will ask the user to input a word or
typed goodbye to quit the program. The first part is done the problems
is that how can i find the longest word?
example:
Type a word (or goodbye to quit): Hello
Type a word (or goodbye to quit): Hello Hello
Type a word (or goodbye to quit): goodbye

The longest word is “Hello Helloâ€

can someone help me with my simple program?

Code:
loop do
puts "Type a word ( or goodbye to quit):"
$_ = gets.chomp

break if $_ == "goodbye"

end

Attachments:
http://www.ruby-forum.com/attachment/4923/test.rb
 
D

Damjan Rems

longest = ''
loop do
puts "Type a word ( or goodbye to quit):"
$_ = gets.chomp
break if $_ == "goodbye"
longest = $_ if $_.size > longest.size
end
p "Longest is #(longest)"
 
B

Bruce Wayner

Damjan said:
longest = ''
loop do
puts "Type a word ( or goodbye to quit):"
$_ = gets.chomp
break if $_ == "goodbye"
longest = $_ if $_.size > longest.size
end
p "Longest is #(longest)"


Thank U very much! for the fast response
sorry i forgot to include if longest word has been select how can i get
the length of that longest word example: Helo Helo (9 characters)

Cheers
 
J

Jean-Julien Fleck

Hello,
p "Longest is #(longest)"

You need accolades and not parenthesis here.
Also, 'puts' might be better in this case ('p' uses 'inspect' and will
display the string between "..")

puts "Longest is #{longest}"

Cheers,


--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 
G

Gianfranco Bozzetti

Bruce said:
Thank U very much! for the fast response
sorry i forgot to include if longest word has been select how can i get
the length of that longest word example: Helo Helo (9 characters)

Cheers

Change p "Longest is #(longest)" with
puts "Longest is #(longest) of size #{longest.size}"

HTH gfb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,184
Members
46,721
Latest member
DollieSawt

Latest Threads

Top