Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: colon before vs after [duplicate]

Tags:

ruby

When using Ruby, I keep getting mixed up with the :.

Can someone please explain when I'm supposed to use it before the variable name, like :name, and when I'm supposed to use it after the variable like name:?

An example would be sublime.

like image 617
FloatingRock Avatar asked Jul 09 '14 19:07

FloatingRock


People also ask

What do double colons mean in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

What Does a colon after a variable mean in Ruby?

Just to add - defining it as consumable: as opposed to consumable: "some default value" implies that consumable is a required parameter.

What Does a colon before a variable mean in Ruby?

Learn what a colon before a variable means in Ruby This means that two symbols with the same name always refer to the same object.

What does :: In Ruby mean?

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.


1 Answers

This has absolutely nothing to do with variables.

:foo is a Symbol literal, just like 'foo' is a String literal and 42 is an Integer literal.

foo: is used in three places:

  • as an alternative syntax for Symbol literals as the key of a Hash literal: { foo: 42 } # the same as { :foo => 42 }
  • in a parameter list for declaring a keyword parameter: def foo(bar:) end
  • in an argument list for passing a keyword argument: foo(bar: 42)
like image 163
Jörg W Mittag Avatar answered Sep 18 '22 02:09

Jörg W Mittag