Skip to content

Instantly share code, notes, and snippets.

@kmandreza
Created January 30, 2013 00:47
Show Gist options
  • Save kmandreza/4669573 to your computer and use it in GitHub Desktop.
Save kmandreza/4669573 to your computer and use it in GitHub Desktop.
When you need to operate on a Ruby Array, you can accomplish just about anything you can imagine with the each method. Often, though, using each is not the best way to work with Arrays. For example, when you find yourself adding conditional logic inside your each block, or using each to search, sort, or transform the Array, consider the power of…
# Print the 1st, 3rd, 5th, 7th, etc. elements of a list on separate lines.
def print_odd_indexed_integers(array)
array.each_with_index do |item, index|
if index.even?
#should be .odd? in the spec
puts item
end
end
end
# Return the odd numbers from a list of integers.
def odd_integers(arr)
arr.select do |item, index|
if item.odd?
puts item
end
end
end
# Return the first number from an Array that is less than 10.
def first_under(array, limit)
array.find do |item|
item < limit
end
end
# Take an Array of Strings and return a new Array with an exclamation point appended to each String.
def add_bang(array)
end
# Calculate the sum of an Array of numbers.
def sum(array)
end
# Reorganize an Array of the elements into groups of 3, and then sort each group alphabetically.
def sorted_triples(array)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment