What is the colon operator in Ruby?
:foo
is a symbol named "foo". Symbols have the distinct feature that any two symbols named the same will be identical:
"foo".equal? "foo" # false
:foo.equal? :foo # true
This makes comparing two symbols really fast (since only a pointer comparison is involved, as opposed to comparing all the characters like you would in a string), plus you won't have a zillion copies of the same symbol floating about.
Also, unlike strings, symbols are immutable.
Significance of colon : in Ruby
A colon denotes a "symbol". A symbol is like a string, but it is immutable (you can't change its contents). Behind the scenes, it also takes up less memory, since a symbol only needs to exist once in memory (i.e., two strings called "length" will exist twice in memory, but two symbols called :length will point to the same object).
What is the colon classified as in Ruby? It's not an operator
Parsing a program takes place in two steps:
- turning the sequence of characters into sequence of tokens, and
- turning the sequence of tokens into a syntactic tree.
Operators, simple object literals, keywords (such as begin
), =>
are all tokens, and are handled in step 2. Tokens have internal names in Ruby C code.
However, the colon as part of a named parameter in a method or a symbol key in a hash is handled in step 1, and is not a token; it does not have a particular name.
What is the colon 'operator' doing in this example?
The colon isn't an operator inside bar
, it is simply a Symbol
literal that uses string interpolation to build the Symbol
. Some Symbol
s need to be quoted to avoid syntax issues, for example:
:'a+b'
You can also use double quotes with this syntax and those quotes behave just like double quotes for strings so they support string interpolation. So this:
:"#{b}bar"
is equivalent to:
"#{b}bar".to_sym
or
(b.to_s + 'bar').to_sym
If you #inspect
your value you'll get a better idea of what it contains:
puts c.inspect
# :foobar
Ruby: colon before vs after
You are welcome for both, while creating Hash
:
{:name => "foo"}
#or
{name: 'foo'} # This is allowed since Ruby 1.9
But basically :name
is a Symbol
object in Ruby.
From docs
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" }
Ruby's double colon (::) operator usage differences
Constants in Ruby are nested like files and directories in filesystem. So, constants are uniquely identified by their paths.
To draw an analogy with the file system:
::Rails::Engine #is an absolute path to the constant.
# like /Rails/Engine in FS.
Rails::Engine #is a path relative to the current tree level.
# like ./Rails/Engine in FS.
Here is the illustration of possible error:
module Foo
# We may not know about this in real big apps
module Rails
class Engine
end
end
class Engine1 < Rails::Engine
end
class Engine2 < ::Rails::Engine
end
end
Foo::Engine1.superclass
=> Foo::Rails::Engine # not what we want
Foo::Engine2.superclass
=> Rails::Engine # correct
How to understand the colon operator usage in a Ruby class
validates
is implemented as a class method in ActiveModel::Validations
.
The ActiveModel::Validations
module is included in ApplicationRecord
, therefore you are able to call that method when your User
class is loaded.
validates
accepted an array and treats the last element of that array as an options hash (if the last element is an hash).
What is Ruby's double-colon `::`?
::
is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:
module SomeModule
module InnerModule
class MyClass
CONSTANT = 4
end
end
end
You could access CONSTANT
from outside the module as SomeModule::InnerModule::MyClass::CONSTANT
.
It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot .
).
Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes
ruby on rails, colon at back or front of variables
What i have understand so far is that
:variable
in ruby, is to say that this variable will not be able to change, which is similar to constant in other language.
I'm not sure if I understand that statement. In Ruby, constants start with an uppercase letter:
Foo = 1
Reassignment generates a warning:
Foo = 1
Foo = 2 #=> warning: already initialized constant Foo
Variables start with a lowercase letter and reassignment doesn't cause a warning (they are supposed to change):
foo = 1
foo = 2 # no warning
Symbols start with a colon:
:a_symbol
:Uppercase_symbol
:"i'm a symbol, too"
They often represent static values, e.g. :get
and :post
. Symbols are memory efficient, because they are created only once - the same symbol literal always returns the same object. Checking if two symbols are equal is a cheap operation.
Both
key:
andmethod:
(...) What does that this represent?
This is an alternate syntax for hashes. You can type it in IRB to see the result:
{ foo: 1, bar: 2 }
#=> {:foo=>1, :bar=>2}
There are double colons inbetween variables? now I am guessing that
Blog:
is one variable, and:Application
is constant.
No, Blog
and Application
are both constants and ::
is the scope resolution operator. It can be used to access nested constants, e.g.:
module Foo
class Bar
BAZ = 123
end
end
Foo::Bar::BAZ #=> 123
Related Topics
How to Change Default Timezone For Active Record in Rails
Do..End VS Curly Braces For Blocks in Ruby
Trying to Learn/Understand Ruby Setter and Getter Methods
Ruby: Inherit Code That Works With Class Variables
Usage of Attr_Accessor in Rails
Why Am I Getting Objects Printed Twice
When Should I Use Struct Vs. Openstruct
Method to Parse HTML Document in Ruby
Cannot Load Such File - Zlib Even After Using Rvm Pkg Install Zlib
How to Redirect to a 404 in Rails
Difference Between \A \Z and ^ $ in Ruby Regular Expressions
Confusion With the Assignment Operation Inside a Falsy 'If' Block
In Ruby on Rails, to Extend the String Class, Where Should the Code Be Put In
Require': Cannot Load Such File - 'Nokogiri\Nokogiri' (Loaderror) When Running 'Rails Server'
What's the Best Way to Model Recurring Events in a Calendar Application