MC logo

More List Ops

^  Ruby Example Code

<<Regular Expressions II iter2.rb Polynomial Evaluator>>
fred = [ 4, 9, 18, 3, 87, 9, 12 ]
alex = [ 'Susan', 'Joe', 'Alex', 'Alice', 'Sam' ]

# Compute a new array with each member of fred doubled.
fred = fred.map { |x| 2 * x }
print fred.join(" "), "\n"

# Create a new alex adding " went away" to each member.  Then join and
# print the result.
print (alex.map { |z| z + " went away" }).join("  "), "\n"

# Print the members of fred which are more than five and less than 20.
print (fred.select { |z| z > 5 && z < 20 }).join(" "), "\n"

# Print the lengths of the members of alex that start with A or end with e.
print ((alex.select { |n| n =~ /^A/ || n =~ /e$/ }).map { |z| z.length }).
        join(" "), "\n"

# Update alex by surround each of its members with [ ]
alex.map! { |a| "[" + a + "]" }
print alex.join(" "), "\n"

The built-in Array class contains a number of iterators which work on the entire list and return a list result. Two important ones are map, which runs the code block on each member of the list, and returns the list of results from those operations. The other is select, which also runs a code block on each member of the list. This block should return a boolean, and a new list is build of only those members for which the code block produces true. The code block can be thought of as a filter which decides, for each member, if it should be retained.

The plain forms, map and select return a new array. The emphatic forms, map! and select! update the list.
<<Regular Expressions II Polynomial Evaluator>>