Single line if statement boolean option


In the example of a single-line if-statement:

action if boolean

I want to know how to use a boolean expression to evaluation a method parameter that is a string.

for example:

def method(parameter)
puts “response if true” if parameter == "my input"

but Ruby doesn’t like the “my input” syntax in the method definition. Perhaps I need to turn the parameter into a symbol?


Please help us by including a link to the exact exercise you are on (copy the URL from the location bar and paste it into a post). Thanks.

An example to try…

def foo(bar)
  "FooBar" if bar == 'bar'

puts foo('bar')    # FooBar


But really, i’m looking to deepen my understanding of the lesson

I tried your example; Ruby said ‘bar’ is an undefined local variable or method… so i probably need to initialize the parameter as an instance variable?


I did the example in the Learn Ruby environment with expected output. No variable needed.

Ruby implicitly returns the last line, hence no return keyword in my code. It is returning “FooBar” or it is returning nothing (nil).


You didn’t answer my question, but I understand your limitations.


I’ve elicited a more “focused” response from a friend.


Okay, now I see where you are…

return "n must be greater than 0." if n <= 0

Or more simply,

def first_n_primes(n)
  return "n must be an integer." unless n.is_a? Integer
  return "n must be greater than 0." unless n > 0
  Prime.first n


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.