Is there a way to use ternary conditional expression for this exercise?


I know this may seems unnecessary and i did manage to get the correct answer ( my_array.each {|x| puts x if x % 2 == 0} ). I am just curious is there a way to write the code with ternary conditional expression. However the code i tried below resulted in some error.

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

my_array.each do |x|
    puts (x % 2 == 0) ? x


Ternary has three parts (literally means three parts) but you've only used two of them

puts would also need to be included, however, it should only be evaluated for some of the numbers


Okay, I understand that the last part is what ruby will execute if the condition is false. So is there a way to tell Ruby that do not do anything if it's false?


You can conditionally evaluate expressions by adding if CONDITION after them, for example, you can make that whole loop not run at all with:

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

my_array.each do |x|
    puts x
end if false  # This loop expression won't run, because the condition is not satisfied

You could even..

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

my_array.each do |x|
    puts x
end if true if true if true if true if true


Sorry for being unclear. Let me ask again.
Okay since ternary conditional expression follows the syntax of

boolean ? Do this if true: Do this if false (three parts)

Since my code puts (x % 2 == 0) ? x has fulfilled the first two parts. What I meant was, is it possible to add in the third part(do this if false) into puts (x % 2 == 0) ? x ? i.e. puts (x % 2 == 0) ? x: (additional code that tells ruby don't do anything if it is false / the third part) . Since the reason why my code doesn't work is due having only two parts. I find it hard to articulate my thoughts in coding probably due to my lack in understanding. Hope you get my question.


Adding if CONDITION after an expression is like a two-part ternary, it only does it if the condition is satisfied

The problem with puts TERNARY-EXPR is that you puts either way, it's unconditional

You would need to do CONDITION ? puts(STUFF TO PRINT) : DO NOTHING, but since you're ignoring the third part you should instead be using if CONDITON

They're both described here:


thank you for the help :slight_smile:


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