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?
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.
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.
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).
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 .
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" }
Depending on the Ruby version, this is either a Hash
literal (1.9) or a keyword argument (2.0+).
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.
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