Subsecciones

Listas de Argumentos de Longitud Variable y Arrays

Sometimes we want to write methods that can accept an arbitrary number of arguments. To do this, we put an * before one of the method’s parameters. Within the body of the method, this parameter will refer to an array that contains the zero or more arguments passed at that position. For example:

# Return the largest of the one or more arguments passed
def max(first, *rest)
  # Assume that the required first argument is the largest
  max = first
  # Now loop through each of the optional arguments looking for bigger ones
  rest.each {|x| max = x if x > max }
  # Return the largest one we found
  max
end

max(1)       # first=1, rest=[]   
max(1,2)     # first=1, rest=[2]  
max(1,2,3)   # first=1, rest=[2,3]

Pasando Arrays a Métodos que Esperan una Lista de Argumentos

# Return the largest of the one or more arguments passed
def max(first, *rest)
  ...
end

data = [3, 2, 1]
m = max(*data)   # first = 3, rest=[2,1] => 3

A veces nos referimos a este uso de * como el operador de splat

m = max(data)   # first = [3,2,1], rest=[] => [3,2,1]

# Convert the Cartesian point (x,y) to polar (magnitude, angle) coordinates
def polar(x,y)
  return [ Math.hypot(y,x), Math.atan2(y,x) ]
end

# Convert polar coordinates to Cartesian coordinates
def cartesian(magnitude, angle)
  [magnitude*Math.cos(angle), magnitude*Math.sin(angle)]
end

x,y = cartesian(*polar(x, y))

Los Enumeradores son Splattables

Los enumeradores Enumerator en son objetos con métodos como each, each_with_index y next:

ruby-1.9.2-head :015 > z = "hello".each_char
 => #<Enumerator: "hello":each_char> 
ruby-1.9.2-head :016 > z.next
 => "h" 
ruby-1.9.2-head :017 > z.next
 => "e" 
ruby-1.9.2-head :022 > z.class.instance_methods(false)
 => [:each, :each_with_index, :each_with_object, :with_index,
     :with_object, :next_values, :peek_values, :next, :peek, :feed,
     :rewind, :inspect]
Los enumeradores en Ruby 1.9 son objetos splattables:
max(*"hello world".each_char)  # => 'w'

Casiano Rodriguez León 2015-01-07