(RUBY) Array as argument list

Post any examples or modules that you want to share here
Post Reply
tulamide
Posts: 2714
Joined: Sat Jun 21, 2014 2:48 pm
Location: Germany

(RUBY) Array as argument list

Post by tulamide »

You may already know that you can use the splat operator followed by an array to define a list of arguments. That's helpful if you have a method that works with any number of arguments:

Code: Select all

def sum *args
   sum = 0
   args.each do |n|
      sum += n
   end
   return sum
end

sum 1, 2, 3, 4, 5, 6
#returns 21


But, it also works the other way round. Imagine, you have an array structured like this

Code: Select all

myArray = [x, y, z, x, y, z, x, y, z]

and a method like this

Code: Select all

def translate x, y, z
   n = x * z + y * z
   #do cool stuff
end


You can easily use the array without intermediate steps like so

Code: Select all

translate *myArray[0..2]
#takes the first 3 elements of myArray and passes them as arguments


Happy Programming :D
"There lies the dog buried" (German saying translated literally)
Post Reply