Ruby operations on enumerables


 
# Arrays, ranges, hashes are instances of Enumrable 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| "I love #{y}!"} # not quite what we want...

puts digits.inject(0) {|sum, n| sum + n }
puts (1..6).inject(1) {|prod, n| prod * n }


CSci 4651 course.

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.