Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon in arguments of a method call - Ruby

when looking to some Ruby code I found the following method:

def connection
    unless @_mc_connection && valid? && @_ns_version == get_version
      @_mc_connection = ::Dalli::Client.new(self.dalli_servers, self.dalli_options.merge(namespace: namespace))
    end
    @_mc_connection
  end

My question is about the use of dalli_options.merge(namespace: namespace). What is the purpose of the colon here? Is an hash member?

like image 861
pinker Avatar asked Nov 27 '13 17:11

pinker


People also ask

What is colon mean in Ruby?

What is symbol. Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.

What does the :: mean in Ruby?

The use of :: on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong class defined in whatever the current module is.

What is * args in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

What happens when you call a method in Ruby?

In ruby, the concept of object orientation takes its roots from Smalltalk. Basically, when you call a method, you are sending that object a message. So, it makes sense that when you want to dynamically call a method on an object, the method you call is send .


3 Answers

What is the purpose of the colon here? Is an hash member?

Yes, it is a Hash object.

A Hash can be easily created by using its implicit form:

grades = { "Jane Doe" => 10, "Jim Doe" => 6 }

Hashes allow an alternate syntax form when your keys are always symbols. Instead of

options = { :font_size => 10, :font_family => "Arial" }

You could write it as:

options = { font_size: 10, font_family: "Arial" }
like image 87
Arup Rakshit Avatar answered Oct 04 '22 12:10

Arup Rakshit


Depending on the Ruby version, this is either a Hash literal (1.9) or a keyword argument (2.0+).

like image 43
Jörg W Mittag Avatar answered Oct 04 '22 13:10

Jörg W Mittag


The colon is part of the symbol syntax.

The following are equivalent:

namespace:   #only valid inside a hash

and

:namespace

With the former, the 'hash rocket' operator (=>) can be omitted (and usually is, for ease of reading).

However, this is only the case when your keys are symbols. If your keys are strings, as in

{ 'namespace' => 'api' }

the hash rocket is required.

like image 24
Jake Romer Avatar answered Oct 04 '22 12:10

Jake Romer