Skip to content

Instantly share code, notes, and snippets.

@andymatuschak
Created July 14, 2010 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andymatuschak/475014 to your computer and use it in GitHub Desktop.
Save andymatuschak/475014 to your computer and use it in GitHub Desktop.
Ruby expression values and a lesson on newlines
# In Ruby, every expression (even ifs) has a value!
print 'What is your name? '
name = gets.chomp
name_response = if name == 'Suzanne'
then 'Oh man, ' + name + ' you are awesome'
else 'You, ' + name + ', are not nearly as cool as Suzanne.'
end
print name_response
# Now, you notice that when you run the script, you get this kind of effect:
# Unicycle:~ andym$ ruby test.rb
# What is your name? Suzanne
# Oh man, Suzanne you are awesomeUnicycle:~ andym$
# Hm. Why is the last line like that? Well, why do you say gets.chomp instead of
# just gets? The input has a newline at the end, and you don't want that. But
# you *do* want it here.
# Try one, use the newline symbol:
print 'What is your name? '
name = gets.chomp
name_response = if name == 'Suzanne'
then 'Oh man, ' + name + ' you are awesome.\n'
else 'You, ' + name + ', are not nearly as cool as Suzanne.\n'
end
print name_response
# Result:
# Unicycle:~ andym$ ruby test
# What is your name? Andy
# You, Andy, are not nearly as cool as Suzanne.\nUnicycle:~ andym$
# Whoa! Why'd that happen? Well, turns out 'str' and "str" aren't quite the same:
# The former doesn't interpret any special stuff (including escape sequences
# like \n), and the latter does.
# Try two:
print 'What is your name? '
name = gets.chomp
name_response = if name == 'Suzanne'
then 'Oh man, ' + name + " you are awesome.\n"
else 'You, ' + name + ", are not nearly as cool as Suzanne.\n"
end
print name_response
# This works as expected, but now we have that newline in both places.
# We could go back to the original code but use this instead of the last line:
print name_response + "\n"
# Or we can use print's friend, puts, which automatically adds a newline:
puts name_response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment