Homepage / Notes / Computer Science / Programming Languages / Ruby
Can use both single quotes '
or double quotes "
.
/!\ Must use double quotes
= 'world'
name = "hello #{name}" str
hello world
= 'hello '
str << 'world' str
hello world
= 'hello'.freeze
str .frozen? str
true
= 'hello'.freeze
str << ' world' str
=can't modify frozen String: "hello" (FrozenError)=
# frozen_string_literal: true
This line placed at the beginning of a file will freeze all strings in the file.
See also: https://docs.ruby-lang.org/en/3.0.0/doc/syntax/comments_rdoc.html#label-Magic+Comments
"Damien".chars
["D", "a", "m", "i", "e", "n"]
"String to be split".split
["String", "to", "be", "split"]
"String,to,be,split".split(',')
["String", "to", "be", "split"]
https://docs.ruby-lang.org/en/3.0.0/Array.html
= [1, 2, 3]
a = [4, 5, 6]
b
.push(*b) a
[1, 2, 3, 4, 5, 6]
= []
list
1..5).each {|i| list << i}
(
list
[1, 2, 3, 4, 5]
[1, 2, 3] => [a, b, c]
c
3
Symbols are immutable, unique identifiers represented by a name preceded by a colon (:
).
:hello
:hello
You can easily convert a string to a symbol and vice-versa:
:name.to_s
name
"name".to_sym
:name
https://ruby-doc.org/core-3.0.0/Hash.html Older syntax, "hash rocket":
= {:foo => 0, :bar => 1} h
{:foo=>0, :bar=>1}
= {foo: 0, bar: 1} h
{:foo=>0, :bar=>1}
= {foo: 0, bar: 1}
h [:foo] h
0
= {foo: 0, bar: 1}
h .fetch(:foo) h
0
Can provide a default:
= {foo: 0, bar: 1}
h .fetch(:baz, "Oops") h
Oops
= {foo: {deepfoo: {nested: 'deep_nested_value'}}, bar: 1}
h .dig(:foo, :deepfoo, :nested) h
deep_nested_value
= {foo: 0, bar: 1}
h .delete(:foo) # this returns the deleted key's value, so 0 in this case
h h
{:bar=>1}
= {first: 'value'}
a = {second: 'another value'}
b .merge(b) a
{:first=>"value", :second=>"another value"}
= {first: 'value'}
a = {**a, second: 'another value'} b
{:first=>"value", :second=>"another value"}
= {foo: 0, bar: 1}
h .keys h
[:foo, :bar]
= {foo: 0, bar: 1}
h .values h
[0, 1]
Starting from Ruby 3.1
= 8
x = 9
y
{x:, y:}
{:x=>8, :y=>9}
= { name: 'Damien', age: 28, role: 'CEO' }
user .slice(:name, :age) user
{:name=>"Damien", :age=>28}
= { name: 'Damien', age: 28, role: 'CEO' }
user .except(:role) user
{:name=>"Damien", :age=>28}
{a: true, b: false}.transform_values(&:!)
{:a=>false, :b=>true}
= {foo: 0, bar: 1}
h .each do |key, value|
hputs "#{key}: #{value}"
end
foo: 0
bar: 1
= {foo: 0, bar: 1}
h .any? { |key, value| value > 0 } h
true
Removes any null values
= {foo: 0, bar: nil}
h .compact h
{:foo=>0}
= {foo: 0, bar: nil}
h puts h.empty?
= {}
h puts h.empty?
false
true
def say_hello(name)
puts "hello #{name}"
end
'Damien') say_hello(
hello Damien
def greet_name(name = 'John Doe')
puts "hello #{name}"
end
greet_name'Damien') greet_name(
hello John Doe
hello Damien
def greet_name(greeting:, name:)
puts "#{greeting}, #{name}"
end
name: 'Damien', greeting: 'hi') greet_name(
hi, Damien
Starting from Ruby 3.1
def greet_name(greeting:, name:)
puts "#{greeting}, #{name}"
end
= 'hi'
greeting = 'Damien'
name greet_name(name:, greeting:)
hi, Damien
Starting from Ruby 3.0
def increment(x) = x + 1
42) increment(
43
https://docs.ruby-lang.org/en/3.0.0/doc/syntax/control_expressions_rdoc.html
= 0
x
while x < 5
puts x
+= 1
x end
0
1
2
3
4
= 0
x
until x == 5
puts x
+= 1
x end
0
1
2
3
4
= [1, 2, 3, 4, 5]
x
for i in x do
puts i
end
1
2
3
4
5
= ['Bob', 'Joe', 'Steve', 'Janice', 'Susan', 'Helen']
names
.each { |name| puts name } names
Bob
Joe
Steve
Janice
Susan
Helen
https://docs.ruby-lang.org/en/3.0.0/Enumerable.html
= ['a', 'b', 'c']
x
.any?('a') x
true
.any?('d') x
false
[1, 2, 3].min
0
[1, 2, 3].max
3
[1, 2, 3].minmax
[1, 3]
[3, 2, 1].sort
[1, 2, 3]
[1, 2, 3, 4, 5].filter {|i| i >= 3}
[3, 4, 5]
= Hash.new
hash
['a', 'b', 'c'].each_with_index {|item, index|
[index] = item
hash}
hash
{0=>"a", 1=>"b", 2=>"c"}
1..10).each_with_object([]) {|i, a| a << i*2} (
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[1, 2, 3, 4, 5].map {|i| i * 2}
[2, 4, 6, 8, 10]
[1, 2, 3, 4, 5].reduce(:+)
15
A block of code that can be passed to a method.
[1, 2, 3].each { |num| puts num }
1
2
3
[1, 2, 3].each do |num|
puts num
end
1
2
3
= Proc.new { |num| num * 2 }
double .call(5) double
10
= lambda { |x| x * 3 }
l .call(3) l
9
A shorter syntax is available using ->
:
= ->(x) { x * 3 }
l .call(5) l
15
Starting from Ruby 3.1
[1, 2] => _, x
x
2
{ name: 'Damien', age: 28 } => {name:}
name
Damien
https://docs.ruby-lang.org/en/3.0.0/Class.html
class Greeter
def initialize(name)
@name = name.capitalize
end
def salute
return "Hello #{@name}!"
end
end
# Create a new object
= Greeter.new("world")
g
.salute g
Hello World!
@foobar
?The variable which name begins which the character `@', is an instance variable of self. Instance variables are belong to the certain object. Non-initialized instance variables has value nil.
attr_reader
To avoid having to call @name
with the @
, attr_reader
can be used:
class Greeter
attr_reader :name
def initialize(name)
@name = name.capitalize
end
def salute
return "Hello #{name}!"
end
end
# Create a new object
= Greeter.new("world")
g
.salute g
Hello World!
Greeter.instance_methods(false)
:salute | :name |
https://docs.ruby-lang.org/en/3.0.0/Module.html
module Greeter
def self.salute
return "Hello World!"
end
end
# Output "Hello World!"
Greeter.salute
Hello World!
::
?Allow to access items in modules or class-level items in classes. Example:
module SomeModule
module InnerModule
class MyClass
CONSTANT = 4
end
end
end
SomeModule::InnerModule::MyClass::CONSTANT
4
You could access CONSTANT
by: SomeModule::InnerModule::MyClass::CONSTANT
Time.now
2021-05-31 21:31:48.883643 -0400
Time.now.to_i
1622511129
https://noteflakes.com/articles/2021-10-20-explaining-ruby-fibers
https://brunosutic.com/blog/ruby-fiber-scheduler
a ||= b means: If a
is undefined
, nil
or false
, assign b
to a
. Otherwise, keep a
intact.
Interactive Ruby Shell, the REPL of Ruby!
https://rubyonrails.org/ Web Framework
https://guides.rubyonrails.org/caching_with_rails.html To enable caching in dev: rails dev:cache
https://guides.rubyonrails.org/caching_with_rails.html#low-level-caching Using Rails.cache.fetch
, both reading and writing is taken care of.
reload!
is a method to reload your application code in the current console session.
rails console --sandbox
shortcut: rails c -s
Any modifications will be rolled back on exit
https://hanamirb.org/ Alternative to Rails
state_machines
https://github.com/state-machines/state_machines
Adds support for creating state machines for attributes on any Ruby class
https://blog.appsignal.com/2022/06/22/state-machines-in-ruby-an-introduction.html
https://github.com/ankane/polars-ruby
🔥 Blazingly fast DataFrames for Ruby, powered by Polars
https://github.com/seanlerner/ruby-and-rails-learning-plan
https://learnrubythehardway.org/book/ex13.html
by Jeremy Evans