Make delicious recipes!

Iterating over arrays and maps in ruby





# Use .each to iterate over an array
[1,2,3].each { |n| print (n+n).to_s + "\n"}
=> 2
=> 4
=> 6


# Use .each_with_index to get the array index as well as the array item in the loop.
["a","b","c"].each_with_index { |n, i| print "#{i}) " + (n+n).to_s + "\n"}
=> 0) aa
=> 1) bb
=> 2) cc


# Filtering an array can be done using .select
[1,2,3,4,5].select {|item| item.even?}
=> [2, 4]


# All elements of an array can be operated upon using .collect
[1,2,3,4,5].collect {|item| item*2}
=> [2, 4, 6, 8, 10]


# Ruby supports associative arrays (or maps in some other languages)
my_hash = {"a" => 1, "b" => 2, "c" => 3}
=> {"a"=>1, "b"=>2, "c"=>3}

# .select works on associative arrays
my_hash.select{|key, val| val <= 2}
=> {"a"=>1, "b"=>2}

# .collect too works on associative arrays
my_hash.collect{|key, val| key=key, val * val, key+val.to_s}
=> [["a", 1, "a1"], ["b", 4, "b2"], ["c", 9, "c3"]]


# Note: .map and .collect in ruby are aliases, use whatever you find more convenient

# map/collect return a new array while map!/collect! modify the input array
# In the following example, array "a" remains unchanged and a.map returns a new array
a = [1,2,3]
new_arr = a.map{|n|n*n}
a
=> [1, 2, 3]
new_arr
=> [1, 4, 9]


# Where as, if you use map! then it changes the original array 
new_arr = a.map!{|n|n*n}
a
=> [1, 4, 9]
new_arr
=> [1, 4, 9]

# Similarly collect! will change the existing array once more:
new_arr = a.collect!{|n|n*n}
a
=> [1, 16, 81]
new_arr
=> [1, 16, 81]

# You can also use the short-hand ampersand
["amy", "bob", "catherine"].map(&:capitalize)
=> ["Amy", "Bob", "Catherine"]


####################################################
# Use .inject to remember the result as you loop
####################################################

[1,2,3].inject {|running_result, item| running_result += item}
=> 6

# You can initialize the running_result with a value if you want 
[1,2,3].inject(10) {|running_result, item| running_result += item}
=> 16

# .reduce is an alias for .inject


##############################################################
# Check whole array for a condition - any?, all?, none?
##############################################################

# Check if there is any element matching the given condition
[1,2,3].any? {|n|n>2}
=> true
# Check if all elements match the given condition
[1,2,3].all? {|n|n>2}
=> false
# Check if no element matches the given condition, opposite of "any?"
[1,2,3].none? {|n|n>2}
=> false


##############################################################
# Find
##############################################################
[1,2,3].find {|n|n>2}
=> 3


##############################################################
# Group by
##############################################################
[1,2,3].group_by{|n| n.to_s(2)}
=> {"1"=>[1], "10"=>[2], "11"=>[3]}


# rjust is short for right-justification and can be used to pad a string with
# given characters so that the resulting string is of the given length
[1,2,3].group_by{|n| n.to_s(2).rjust(3,'0')[1]}
=> {"0"=>[1], "1"=>[2, 3]}


##############################################################
# grep
##############################################################
["amy", "bob", "cathy"].grep(/a[mt]/)
=> ["amy", "cathy"]
["amy", "bob", "cathy"].grep(/a[mt]/).grep(/^a.*y$/)
=> ["amy"]

##############################################################
# Use * with the last argument to create an argument with
# variable number of arguments.
##############################################################
def var_args_method (arg1, arg2, *more_args)
  puts "1) #{arg1}"
  puts "2) #{arg2}"
  more_args.each_with_index {|item, i| puts "#{i}) #{item}"}
end
var_args_method 1,2,3,4,5
=> 1) 1
=> 2) 2
=> 0) 3
=> 1) 4
=> 2) 5







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal