In Ruby what does = mean and how does it work?
=>
separates the keys from the values in a hashmap literal. It is not overloadable and not specifically connected to symbols.
A hashmap literal has the form {key1 => value1, key2 => value2, ...}
, but when used as the last parameter of a function, you can leave off the curly braces. So when you see a function call like f(:a => 1, :b => 2)
, f
is called with one argument, which is a hashmap that has the keys :a
and :b
and the values 1
and 2
.
what does ? ? mean in ruby
Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false.
When you write a function that can only return true or false, you should end the function name with a question mark.
The example you gave shows a ternary statement, which is a one-line if-statement. .nil?
is a boolean function that returns true if the value is nil and false if it is not. It first checks if the function is true, or false. Then performs an if/else to assign the value (if the .nil?
function returns true, it gets nil as value, else it gets the File.join(root_dir, '/')
as value.
It can be rewritten like so:
if root_dir.nil?
prefix = nil
else
prefix = File.join(root_dir, '/')
end
What is the Ruby = (spaceship) operator?
The spaceship operator will return 1
, 0
, or −1
depending on the value of the left argument relative to the right argument.
a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return nil
It's commonly used for sorting data.It's also known as the Three-Way Comparison Operator. Perl was likely the first language to use it. Some other languages that support it are Apache Groovy, PHP 7+, and C++20.
What does ||= mean?
Basically, a ||= b
means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby)
, it is similar to a = b unless a
, except it will always evaluate to the final value of a
(whereas a = b unless a
would result in nil
if a
was true-ish).
What does :: mean in Ruby syntax?
Ruby :: (double semi colons)
Top level constants are referenced by double colons
class TwelveDaysSong
end
a = TwelveDaysSong.new
#I could wrote it like this too
a = ::TwelveDaysSong.new
module Twelve
class TwelveDaysSongs
end
end
b = Twelve::TwelveDaysSong.new
#b is not equal to
a = ::TwelveDaysSong.new
#neither
a = TwelveDaysSong.new
Classes are constant too so if you have a constantHELLOWOLRD = 'hw'
you could call it like this ::HELLOWORLD
What do =~ and /\ mean in Ruby?
=~
is known as the "match operator" and can be used to match a string against a regular expression.
The /\
is actually part of two separate things. /
denotes the start of a regular expression and \A
is known as an "anchor" and is saying "match from the beginning of the string."
edit: This is a link to the documentation that should help you understand more code like you posted.
thank you to Wayne Conrad for a correction on '/\'
What does the * (star) mean in Ruby?
Variable Length Argument List, Asterisk Operator
The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.
The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.
What does @@variable mean in Ruby?
A variable prefixed with @
is an instance variable, while one prefixed with @@
is a class variable. Check out the following example; its output is in the comments at the end of the puts
lines:
class Test
@@shared = 1
def value
@@shared
end
def value=(value)
@@shared = value
end
end
class AnotherTest < Test; end
t = Test.new
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2
x = Test.new
puts "x.value is #{x.value}" # 2
a = AnotherTest.new
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3
You can see that @@shared
is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared
, with one @
, would not be.[Update]
As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class
class, but only the instance of the Class
class you're working with. An example:
class Polygon
class << self
attr_accessor :sides
end
end
class Triangle < Polygon
@sides = 3
end
class Rectangle < Polygon
@sides = 4
end
class Square < Rectangle
end
class Hexagon < Polygon
@sides = 6
end
puts "Triangle.sides: #{Triangle.sides.inspect}" # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides: #{Square.sides.inspect}" # nil
puts "Hexagon.sides: #{Hexagon.sides.inspect}" # 6
I included the Square
example (which outputs nil
) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.
What does #{ } mean in Ruby?
It is used for String interpolation: ( wikipedia, ctrl+f "ruby" )
apples = 4
puts "I have #{apples} apples"
# or
puts "I have %s apples" % apples
# or
puts "I have %{a} apples" % {a: apples}
The output will be:I have 4 apples
String interpolation, Definition:
In Ruby, string interpolation refers to the ability of double-quoted strings to execute Ruby code and replace portions of that strings (denoted by #{ ... }) with the evaluation of that Ruby code.It is the most common way to inject data (usually the value of a variable, but it can be the evaluation of any Ruby code) into the middle of a string.
A thing to know:
puts "This User name is #{User.create(username: 'Bobby')}!"
This will make an implicit call of .to_s
on the User's instance object.If you defined the method .to_s
on the User model:
class User
def to_s
self.username
end
It would output:puts "This User name is #{User.create(username: 'Bobby')}"
# => "This User name is Bobby"
What does ||= (or-equals) mean in Ruby?
This question has been discussed so often on the Ruby mailing-lists and Ruby blogs that there are now even threads on the Ruby mailing-list whose only purpose is to collect links to all the other threads on the Ruby mailing-list that discuss this issue.
Here's one: The definitive list of ||= (OR Equal) threads and pages
If you really want to know what is going on, take a look at Section 11.4.2.3 "Abbreviated assignments" of the Ruby Language Draft Specification.
As a first approximation,
a ||= b
is equivalent toa || a = b
and not equivalent toa = a || b
However, that is only a first approximation, especially if a
is undefined. The semantics also differ depending on whether it is a simple variable assignment, a method assignment or an indexing assignment:a ||= b
a.c ||= b
a[c] ||= b
are all treated differently.
Related Topics
Why Slicing The Params Hash Poses a Security Issue on Mass-Assignment
Using a Self-Signed Certificate
Ruby: Is It Acceptable to Put More Than One Class in a File
Pod Install in Xcode Bots Trigger
How to Validate Overlapping Times in Rails with Postgresql
Automating Ssh to Windows with Ruby
How to Calculate a String's Width in Ruby
Securely Display an Image Uploaded with Paperclip Gem
Running Rails Console with Bundle Exec
Using Elasticsearch to Filter Through Tags with Whitespace
How to Handle Omniauth Callbacks in Multiple Environments
Should I Move My Custom Methods to Model from Controller
Static Page Routing in Sinatra (Ruby)
Gem Ransack Doesn't Return Any Results When Searched with Full Name
Ruby: Start Reading at Arbitrary Point in Large File
Ruby - Generate All Two Letter Words