nightfire
nightfire

Reputation: 815

ruby if-else one-liner with "puts" not working

I'm trying to do

    response = gets.chomp
    response == "a" ? puts "yes" : puts "no"

The terminal complains:

syntax error, unexpected ':', expecting keyword_end
    response == "a" ? puts "yes" : puts "no"
                                  ^

What am I doing wrong?

Upvotes: 4

Views: 1185

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110665

Here is your error:

response == "a" ? puts "yes" : puts "no"
  #=> syntax error, unexpected ':', expecting end-of-input
  #   response == "a" ? puts "yes" : puts "no"
  #                           ^

Ruby is looking for the first puts' arguments. Since they are not enclosed in parentheses, she assumes they are in a comma-separated list following puts. The first one is "yes", but there is no comma following "yes", so an exception is raised.

Let's try:

response == "a" ? (puts "yes") : puts "no"
  #=> syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
  #   response == "a" ? (puts "yes") : puts "no"
  #                                          ^

(response == "a" ? puts("yes") : puts "no" raises the same exception.)

I don't know why this doesn't work. The exception says that it is expecting a block (do...end or {..}) or a left parentheses (for enclosing arguments) after the second puts. Kernel#puts calls $stdout.puts. As $stdout returns an IO object, IO#puts is then called, but the doc sheds no light on the problem. Perhaps a reader can offer an explanation.

You could write it as follows:

response == "a" ? (puts "yes") : (puts "no")

or

response == "a" ? puts("yes") : puts("no")

or (best, imo)

puts response == "a"  ? "yes" : "no"

Upvotes: 6

Related Questions