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.
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.
Just to add - defining it as consumable: as opposed to consumable: "some default value" implies that consumable is a required parameter.
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.
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.
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:
Symbol
literals as the key of a Hash
literal: { foo: 42 } # the same as { :foo => 42 }
def foo(bar:) end
foo(bar: 42)
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