Ruby: Map Function to List

By Xah Lee. Date:

Map Function to List

Use array.map {…} method on array object to create a new array. Example:

# -*- coding: utf-8 -*-
# ruby

def ff(n)
 n*n
end

aa = 0..4 # array 0 to 4

p aa.map {|xx| ff xx} # [0, 1, 4, 9, 16]

Use method array.map! {…} to have the original array modified.

Removing Elements in a List

To remove elements, use “select” method and pass it a block.

In Ruby, many methods can take a “block” argument. The “block” is a kind of lambda expression. The syntax has the form: object_name.method_name { |x| expression_on_x}. Example:

# -*- coding: utf-8 -*-
# ruby

aa = 0..10 # a array 0 to 10

p aa.select { |xx| xx % 2 == 0 } # [0, 2, 4, 6, 8, 10]

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables