(RUBY) Array as argument list
Posted: Mon Jun 22, 2015 4:20 pm
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:
But, it also works the other way round. Imagine, you have an array structured like this
and a method like this
You can easily use the array without intermediate steps like so
Happy Programming
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 21But, 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
endYou 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 argumentsHappy Programming