Ruby Enumerable examples



# Arrays, ranges, hashes are instances of Enumerable class

# some useful methods

mixed = [2.3, "hi", 1, 5]
ints = [1, 4, 6, -9, 0]
digits = 0..9
hash1 = {:winter => 'skiing', :spring => 'basketball',
  :summer => 'swimming', :fall => 'hiking'}

# find (or detect), select = find_all
puts ints.find {|x| x < 5}
puts ints.select {|x| x < 5}
puts mixed.find {|x| x < 5}
#puts mixed.select {|x| x < 5}
# returns an array even if the given class is a range or a hash
puts digits.select {|x| x < 5}.class

# map method
puts ints.map {|y| y < 5}
puts mixed.map {|y| y.to_s}
puts hash1.map {|y| "My favorite sport is #{y}"} # not quite what we want...
puts hash1.map {|x, y| "My favorite sport in the #{x} is #{y}"}

puts digits.inject(0) {|sum, n| sum + n }
puts (1..6).inject(1) {|prod, n| prod * n }
puts ints.inject {|m, x| m < x ? m : x}

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.