Skip to content

Instantly share code, notes, and snippets.

@Bahanix
Last active August 15, 2024 11:27
Show Gist options
  • Save Bahanix/0e4d9340fc607b3687d7b87f8839951f to your computer and use it in GitHub Desktop.
Save Bahanix/0e4d9340fc607b3687d7b87f8839951f to your computer and use it in GitHub Desktop.
Ruby syntax 101
# Everything after the '#' character is a comment
# Run these lines in an interactive ruby interpreter (irb) to "feel" them
# Maths
9/2 == 4
9/2.0 == 4.5 # Same as 9.0/2 or 9.0/2.0 or 9.to_f/2
2**8 == 256
# Arrays
[1, 2] + [2, 3] == [1, 2, 2, 3]
[1, 2] - [2, 3] == [1]
[1, 2] | [2, 3] == [1, 2, 3]
[1, 2] & [2, 3] == [2]
a = []
a << "toto"
a == ["toto"]
# Loops
10.times do |n|
puts n
end
10.times { |n| puts n } # oneliner syntax
1.upto(10) do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
(1..10).each do |n|
puts n
end
# Conditions
# Only strongly-typed 'false' and 'nil' (ruby null equivalent) will be rejected by 'if'
# While values like 0 or "" are equivalent to true
condition1 = ""
condition2 = false
if condition1
puts "condition1 is not false nor nil"
elsif condition2
puts "condition1 is false or nil, and condition2 isn't"
else
puts "condition1 and condition2 are both false or nil"
end
# Hashes
# :first_name is a symbol. It's a kind of constant string used as a software internal key.
# Ruby allows two different syntaxes to write hashes whose keys are symbols.
{ first_name: "Julien" } == { :first_name => "Julien" }
{ first_name: "Julien" } != { "first_name" => "Julien" }
my_variable = :first_name
my_hash = { first_name: "Julien" }
my_hash[my_variable] == my_hash[:first_name]
{ first_name: "Julien" }[:first_name] # It also works without variables
my_hash.each{ |key, value| puts value } # You can iterate on key-value pairs
# Functions
# Parentheses for parameters declaration or for function executions are optional.
# If you don't use `return`, then last line of the function will be returned.
def my_function
42
end
my_function == 42
def my_function(i)
i * 2
end
my_function(10) == 20
def my_function(i: 7)
i * 2
end
my_function(i: 10) == 20
my_function == my_function() # 14
def my_function(i:)
i * 2
end
my_function(i: 10) == 20
my_function # ArgumentError (missing keyword: i)
# These all return the same
[1, 2, 3].map{ |i| i * 2 }
["1", "2", "3"].map(&:to_i).map{ |i| i * 2 }
["1", "2", "3"].map{ |i| i.to_i * 2 }
[2, 4, 6]
# Classes / Objects
# @name is an instance variable.
# @@thing would be a class variable, but it is rarely used.
class User
def initialize(name)
@name = name
end
def greet
puts "Bonjour #{@name}"
end
end
user = User.new("Julien")
user.greet == "Bonjour Julien"
user.name # NoMethodError (undefined method `name' for User instance)
# You can define getters and setters
class User
def initialize(name)
@name = name
end
def name
@name
end
def name=(value)
@name = value
end
end
user = User.new("Julien")
user.name == "Julien"
user.name = "Another name"
user.name == "Another name"
# Or you can use `attr_reader`, `attr_writer`, or `attr_accessor`
class User
attr_reader :name
def initialize(name)
@name = name
end
end
user = User.new("Julien")
user.name == "Julien"
user.name = "Another name" # NoMethodError (undefined method `name=' for User instance)
class User
attr_accessor :name
def initialize(name)
@name = name
# `self.name = name` does the same thing, thanks to `attr_accessor`
end
end
user = User.new("Julien")
user.name == "Julien"
user.name = "Another name"
user.name == "Another name"
# About @name vs self.name:
class User
attr_accessor :name
def initialize(name)
@name = name
end
def greet
puts "Bonjour #{self.name}"
# @name and self.name memory is shared, you can mix them (but consistency is prefered!)
# `self.` is mandatory for assignation (`self.name =`),
# but optional for reading (`puts name` is ok).
end
end
# Other considerations:
# Undefined `@foobar` returns `nil`, while undefined `self.foobar` raises.
# Some people don't like `@name` because they prefer to fail fast in case of typo.
# If you don't want to expose `user.name`, you can do:
# `private attr_accessor :name`
# This syntax is pretty new, you won't see it in old codebase.
# In Rails, @variables in controllers are accessible by the views/templates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment