I'm fairly new to code and I have a quick question on Ruby conditionals, specifically Case Expressions. I have a method in which I want to return a string "odd" if the string length is odd and "even" if the string length is even.
Simple stuff I know and I can get the results using a if/else conditional, however the case expression just returns 'nil'. Any help would be greatly appreciated.
when string.length.even? then "even"
when string.length.odd? then "odd"
odd_or_even("Ruby") # Wanting to return even rather than nil
odd_or_even("Rails") # Wanting to return odd rather than nil
You've written your
case statement wrong. It takes two forms, which is unusual compared to other languages. The first form takes an argument, and that argument is compared to all possible cases. The second form is without argument and each case is evaluated independently.
The most minimal fix is this:
def odd_or_even(string) case when string.length.even? then "even" when string.length.odd? then "odd" end end
This was because to Ruby your code looked like this when calling with the argument "Ruby":
def odd_or_even(string) case string when true then "even" when false then "odd" end end
string value does not match
false so you get
nil from a non-matching situation.
You can clean up your code considerably. Consider: Can something be not even and not odd? Not really:
def odd_or_even(string) string.length.even? ? 'even' : 'odd' end