I was browsing through the Camping
codebase when I saw a constructor with a splat being used like this:
class Fruit
def initialize(*)
end
end
I tried looking up "splat with no variable name" on this site and Google, but I couldn't find anything besides info about splat being used with a variable name like this *some_var
, but not without it. I tried playing around with this on a repl, and I tried stuff like:
class Fruit
def initialize(*)
puts *
end
end
Fruit.new('boo')
but that runs into this error:
(eval):363: (eval):363: compile error (SyntaxError)
(eval):360: syntax error, unexpected kEND
(eval):363: syntax error, unexpected $end, expecting kEND
If this question hasn't been asked already, can someone explain what this syntax does?
A parameter with the splat operator converts the arguments to an array within a method. The arguments are passed in the same order in which they are specified when a method is called. A method can't have two parameters with splat operator.
What is the Splat Operator? The * (or splat) operator allows a method to take an arbitrary number of arguments and is perfect for situations when you would not know in advance how many arguments will be passed in to a method. Here's an example: def name_greeting(*names) names. each do |name| puts "Hello, #{name}!"
Single *Splat It can do things like combine arrays, turn hashes and strings into arrays, or pull items out of an array!
When you multiply two numbers in Python you use the multiplication operator “*”. Gives you 4. “*” can also be used for unpacking, in Ruby and other computer languages it is called the splat operator.
It behaves similar to *args but you cant refer to then in method body
def print_test(a, *)
puts "#{a}"
end
print_test(1, 2, 3, 'test')
This will print 1.
Typically a splat like this is used to specify arguments that are not used by the method but that are used by the corresponding method in a superclass. Here's an example:
class Child < Parent
def do_something(*)
# Do something
super
end
end
This says, call this method in the super class, passing it all the parameters that were given to the original method.
source: Programming ruby 1.9 (Dave Thomas)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With