Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a splat operator do when it has no variable name?

Tags:

ruby

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?

like image 312
user886596 Avatar asked Aug 01 '13 02:08

user886596


People also ask

What does the splat operator do in Ruby?

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?

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}!"

What are two uses of the splat operator?

Single *Splat It can do things like combine arrays, turn hashes and strings into arrays, or pull items out of an array!

How do you use splat in Python?

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.


2 Answers

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.

like image 24
Josnidhin Avatar answered Oct 19 '22 22:10

Josnidhin


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)

like image 125
Dillon Benson Avatar answered Oct 19 '22 22:10

Dillon Benson