Ruby if-else one-liner with "puts" does not work

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?

+4
source share
1 answer

Here is your mistake:

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 arguments puts. Since they are not enclosed in parentheses, it assumes that they are in a comma-separated list after puts. The first one is "yes", but after "yes"no comma, therefore an exception is thrown.

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.)

, . , (do...end {..}) ( ) puts. # $stdout.puts. $stdout IO, IO # puts , . , .

:

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

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

(best, imo)

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

Source: https://habr.com/ru/post/1607713/


All Articles