Skip to content

Instantly share code, notes, and snippets.

@brookr
Created May 29, 2013 18:01
Show Gist options
  • Select an option

  • Save brookr/5672341 to your computer and use it in GitHub Desktop.

Select an option

Save brookr/5672341 to your computer and use it in GitHub Desktop.
# Here's a number of different Ruby helper methods can be used to select even numbers from an array
pry(main)> list = [1,2,3,4,5,6,7,8,9,10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pry(main)> list.select { |n| n % 2 == 0 }
=> [2, 4, 6, 8, 10]
pry(main)> list.select { |n| (n % 2).zero? }
=> [2, 4, 6, 8, 10]
pry(main)> list.select { |n| (n.%(2)).zero? } # Uses the modulo method, instead of the operator
=> [2, 4, 6, 8, 10]
pry(main)> list.select { |n| n.even? }
=> [2, 4, 6, 8, 10]
pry(main)> list.reject { |n| n.odd? }
=> [1, 3, 5, 7, 9]
# The following are destructive, and modify the array in place
pry(main)> list = [1,2,3,4,5,6,7,8,9,10]
pry(main)> list.delete_if { |n| n.even? }
=> [2, 4, 6, 8, 10]
pry(main)> list
=> [2, 4, 6, 8, 10]
pry(main)> list = [1,2,3,4,5,6,7,8,9,10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pry(main)> list.reject! { |n| n.even? }
=> [2, 4, 6, 8, 10]
pry(main)> list
=> [2, 4, 6, 8, 10]
pry(main)> list = [1,2,3,4,5,6,7,8,9,10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pry(main)> list.select! { |n| n.even? }
=> [2, 4, 6, 8, 10]
pry(main)> list
=> [2, 4, 6, 8, 10]
# Or we could nilify all the odd values, then strip out all the nils:
pry(main)> list.map { |n| n if n.even? }.compact
=> [2, 4, 6, 8, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment