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] The splat operator (*) beginner's guide
[Ruby] The splat operator (*) beginner's guide
An array is an indexed list of objects. Because arrays are objects, too, an array can contain other arrays. And look at that word! An array is indeed a container.
Code: Select all
myarray = ["a", 1, 2.3, 4..6] #array containing following objects (in this order): String, Fixnum, Float, Range
myarray = [1, 2, [3, [4, 5]], 6]
#um, wow. Contains Fixnum, Fixnum, Array, Fixnum. But that last array again contains
#Fixnum, Array. Which contains Fixnum, Fixnum
#Arrays are cool motherf[peeeeeep]s!Code: Select all
[1, 2, [3, [4, 5]], 6].flatten #results in [1, 2, 3, 4, 5, 6] So, we flattened our array, but it is still an array. A container with an indexed list of objects. But there are occasions, where we need the objects themselves, not the array. For example, a method might define arguments.
Code: Select all
def mymethod(argument_a, argument_b, argument_c)
return argument_a ** argument_b / argument_c
endCode: Select all
myarray = [1, 2, [3, [4, 5]], 6].flatten
result = mymethod(myarray[0], myarray[1], myarray[2]) #passes the fixnums at index 0, 1 and 2, ie the values 1, 2 and 3, as arguments to the methodCode: Select all
myarray = [1, 2, [3, [4, 5]], 6].flatten
result = mymethod(*myarray[0..2]) ##myarray[0..2] creates a new array of exactly the first 3 objects, and the splat operator in front then creates three seperate objects from it: exactly what we need to passCode: Select all
*[1, 2, 3] # means 1, 2, 3 (which is not the same, the three values are now on their own, not part of an array anymore)Code: Select all
def sum_it(*args)
result = 0
args.map { |n| result += n }
return result
endCode: Select all
sum_it(1, 2, 3)
sum_it(6, 8)
etc.And so we can use it as free as you can imagine: by using the splat operator twice.
Code: Select all
def sum_it(*args)
result = 0
args.map { |n| result += n }
return result
end
sum_it(*0..99) #TADAA!Re: [Ruby] The splat operator (*) beginner's guide
You’ve explained it much better than all the tutorials and reference documents I’ve found. I was struggling with this one.
Blocks is another subject that makes me feel a little uneasy. I know a bit in general, but my confidence level is low. So, if you are like a good DJ and allow requests…
Many thanks and cheers!
Spogg