Support

If you have a problem or need to report a bug please email : support@dsprobotics.com

There are 3 sections to this support area:

DOWNLOADS: access to product manuals, support files and drivers

HELP & INFORMATION: tutorials and example files for learning or finding pre-made modules for your projects

USER FORUMS: meet with other users and exchange ideas, you can also get help and assistance here

NEW REGISTRATIONS - please contact us if you wish to register on the forum

Users are reminded of the forum rules they sign up to which prohibits any activity that violates any laws including posting material covered by copyright

(RUBY) Array as argument list

Post any examples or modules that you want to share here

(RUBY) Array as argument list

Postby tulamide » 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:
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)
tulamide
 
Posts: 2692
Joined: Sat Jun 21, 2014 2:48 pm
Location: Germany

Return to User Examples

Who is online

Users browsing this forum: Google [Bot] and 17 guests