From: "David A. Black" Date: 2009-07-22T07:35:28+09:00 Subject: Re: Simple problem with Regular Expression --1926193751-1570023724-1248215714=:22679 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1570023724-1248215714=:22679" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1570023724-1248215714=:22679 Content-Type: TEXT/PLAIN; charset=utf-8; format=flowed Content-Transfer-Encoding: 8BIT Hi -- On Wed, 22 Jul 2009, I単aki Baz Castillo wrote: > El Martes, 21 de Julio de 2009, Max Norman escribi坦: > >> Here is the code: >> fruit = gets.chomp.downcase >> >> if fruit == "orange" >> color = "orange" >> elsif fruit == "apple" >> color = "green" >> elsif fruit == "banana" >> color = "yellow" >> else >> color = "unknown" >> end >> >> fruit.scan(/^./) do |first| >> if first == 'a' || first == 'e' || first = 'i' || first = 'o' || first >> = 'u' >> puts "An #{fruit} is #{color}." >> else >> puts "A #{fruit} is #{color}." >> end >> end > > > Ruby code must be beautiful: > > ---------------------------------- > fruit = gets.chomp.downcase > > case fruit > when "orange" > color = "orange" > when "apple" > color = "green" > when "banana" > color = "yellow" > else > color = "unknown" > end > > if %w{a e i o u}.include?(fruit[0]) > puts "An #{fruit} is #{color}." > else > puts "A #{fruit} is #{color}." > end > > PS: Just valid for 1.9 due to the usage of "fruit[0]". You can change it to fruit[0,1] for backward compatibility. (Getting 1.8 to produce a number is harder, as the recent thread on that topic showed.) Also, consider tightening up the assignment: color = case fruit when "orange" then "orange" when "apple" then "green" when "banana" then "yellow" else "unknown" end And this is just for fun: puts "A#{"n" if "aeiou".include?(fruit[0,1])} #{fruit} is #{color}" :-) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) Training! Intro to Ruby, with Black & Kastner, September 14-17 (More info: http://rubyurl.com/vmzN) --1926193751-1570023724-1248215714=:22679-- --1926193751-1570023724-1248215714=:22679--