In my Ruby Code, Why does my variable inside a string produce a new line? -
ok first day learning , trying create basic questionnaire ruby.
for example, code:
print "what name? " name = gets puts "hello #{name}, welcome." print "what year born in?" year = 2014 year1 = gets.chomp.to_i year2 = year-year1 puts "ok. if born in #{year1}, #{year2} years old."
now if input "joe" name , "1989" birthdate, give me following lines...
hello joe
, welcome.ok. if born in 1989, 25 years old.
i'm confused what's different 2 strings.
you've got right idea way you're processing year user inputs. when type "joe" @ prompt, results in string value "joe\n" getting assigned name
variable. strip newlines off end of string, use chomp
method. change line name = gets.chomp
.
you might want explicitly convert input string. if user ends input control-d, gets
return nil
instead of empty string, , you'll nomethoderror
when call chomp
on it. final code name = gets.to_s.chomp
.
Comments
Post a Comment