Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the odd or even elements out of an array

Tags:

arrays

ruby

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)
like image 318
Reiss Johnson Avatar asked Dec 04 '22 01:12

Reiss Johnson


1 Answers

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
like image 171
Laurens Avatar answered Jan 17 '23 17:01

Laurens