Creates numbers quickly
[*1..10]
# other way around
10.step(by: -1, to: 0).to_a
Sort Reversely
[*1..10].sort_by(&:-@)
The -@
is called unary operator.
Rational and Complex Number
From Rational and Complex module.
42r # Rational(42, 1)
3.14r # 3.14.rationalize
42i # Complex(0, 42)
3.14i # Complex(0, 3.14)
3r + 4i
Since Ruby 2.1.
Function Compositions
<<
and >>
from Ruby 2.6.0.
plus_two = proc { |x| x + 2 }
three_times = proc { |x| x * 3 }
(plus_two << three_times).call(3) # plus_two(three_times(3))
(plus_two >> three_times).call(3) # three_times(plus_two(3))
Initialize Struct with keyword arguments
User = Struct.new(:name, :handle, keyword_init: true)
User.new(name: "Juanito Fatas", handle: "JuanitoFatas")
Since Ruby 2.5: Feature#11925.
Endless Range
array[1..]
(1..).each {|i| puts i }
Since Ruby 2.6: Feature#12912
Beginless Range
array[..42]
(..42).each {|i| puts i }
Since Ruby 2.7.
Count number of elements in array
["a", "b", "c", "b"].tally
#=> {"a"=>1, "b"=>2, "c"=>1}
Since Ruby 2.7.
Delegate arguments
def parent_method(...)
child_method(...)
end
instead of
def parent_method(*args, **options, &block)
child_method(*args, **options, &block)
end
Since Ruby 2.7: Feature#16253.