As per the screenshot, I used the ternary operator to write a method that splits an array into two, based on the condition if the number is even or odd. However, in writing it in the basic block layout, I don’t know where I need to put the “print even” and “print odd” in order for those two arrays to print out when the method is called.
To answer the original question, “just before the final end
statement”. But it hardly seems to be worth creating a separate array for the odds and evens, and you don’t really need the ternary at all.
fives = [5, 10, 15, 20, 25, 30, 35, 40]
def print_evens_and_odds(ary)
p ary.select(&:even?)
p ary.select(&:odd?)
end
print_evens_and_odds fives
PS. please don’t post screenshots, as it makes it harder for people to help you if they can’t cut and paste your code…
The challenge was to separate one array into odds and evens. And the ternary was my own default coding style (i know the block method is easier) idk why but that was my brain did and i just wanted to make sure ci knew how to write it both ways. Thank you for your help
To answer your question based on what code you’ve implemented, think of the scoping. Basically if you create the Even array and the Odd array at the beginning of your function, and then you edit those arrays by adding onto it using an each do loop, you need for your editing loop to finish so you can print out the final results of your array.each loop. Basically before the function ends and after the each do loop! I know it was answered previously but just to go more in depth with the example you’re given.
If you want more confidence in your own answer and being able to conceptually understand it, I would suggest looking into Scopes/Scoping.
I must admit to having a bit of a soft spot for the ternary operator, although many people don’t like it (the designers of Go
for example ). But in this case, the two arrays are only transient and are discarded once the function ends, so just passing an expression to the p
function seemed like the better option. This doesn’t prevent the intermediate arrays from being created of course, but it happens under the covers rather than explicitly in the code.