I've been asked to write a piece of code that returns the odd elements of an array when a the second argument is true
and even elements if it is false
. So far I have written one half and I need a method that can select the odd elements.
def odds_and_evens(string, return_odds)
if return_odds != false
string.chars.to_a
end
end
puts odds_and_evens("abcdefgh", true)
If you add this code you have 2 handy methods to select odd or even values from an array
class Array
def odd_values
values_at(* each_index.select(&:odd?))
end
def even_values
values_at(* each_index.select(&:even?))
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With