Single line if statement boolean option


#1

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"
end

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


#2

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'
end

puts foo('bar')    # FooBar

#3

https://www.codecademy.com/courses/learn-ruby/lessons/the-refactor-factory/exercises/omit-needless-words?action=lesson_resume

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?


#4

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


#5

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

Cheers.

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


#6

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
end

#7

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