why does the space between puts and hello changes the return value? puts("x) or puts (“x”) both return nil so I dont understand whats going on. I would really appreciate some help!
I have written before about this thing. When you call a method, you should always put the parentheses immediately after the method name. Consider these cases:
puts("Hello", 5): In this case, you are calling Kernel.puts with the argument “Hello” and 5. It’s same as puts "Hello", 5.
puts ("Hello", 5): In this case, you are calling Kernel.puts but not passing “Hello” and 5, as an argument directly, instead, the (…) breaks it. In this case, you get SyntaxError. The right way will be puts("Hello", 5).
But if you were to write puts (5), you don’t pass it as argument to puts, immediately, the code inside the parentheses is evaluated first, and then it’s sent as an argument to puts.
Now in your case, you are using short-circuit evaluators, or (||) in this case. So in:
Case 1: You call puts with hello. puts writes to the standard output and returns nil. Which is equivalent of doing nil || true, in that case, you get true.
Case 2: You call puts with "Hello" || true. In Ruby everything except nil and false are truthy. So “Hello” string is truthy, so || will only return the first expression and not the 2nd one. If you do "Hello" && true, then you get true. Anyway, then the returned "Hello" is sent to puts. It’s just like doing puts("Hello" || true).
Thanks for the amazing answer, It is super clear now! Coming from other pl I found really weird that ruby lets me use puts () #method with a space# like that so I imagined something was going on under the hood!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.