Reputation: 2440
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?
Upvotes: 10
Views: 527
Reputation: 4440
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)
Upvotes: 8
Reputation: 12504
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.
Upvotes: 4