Ruby Niceties

[*1..10]

# other way around

10.step(by: -1, to: 0).to_a

[*1..10].sort_by(&:-@)

The -@ is called unary operator.

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.

<< 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))

User = Struct.new(:name, :handle, keyword_init: true)
User.new(name: "Juanito Fatas", handle: "JuanitoFatas")

Since Ruby 2.5: Feature#11925.

array[1..]
(1..).each {|i| puts i }

Since Ruby 2.6: Feature#12912

array[..42]
(..42).each {|i| puts i }

Since Ruby 2.7.

["a", "b", "c", "b"].tally
#=> {"a"=>1, "b"=>2, "c"=>1}

Since Ruby 2.7.

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.

{ a: 1, b: 2 }.transform_keys(&:to_s)
=> { "a" => 1, "b" => 2 }


{ a: 1, b: 2 }.transform_values(&:to_f)
=> { a: 1.0, b: 2.0 }

transform_values Since Ruby 2.4.
transform_keys Since Ruby 2.5.