This article documents several important additions to Ruby Syntax.
1) Block parameters
Option A: Providing a name yourself
a = [ "a", "b", "c" ]
a.each { |x| puts x }
Option B: Use the numbered parameters
a = [ "a", "b", "c" ]
a.each { puts _1 }
Option C: Use "it"
a = [ "a", "b", "c" ]
a.each { puts it }
2) Infinite Ranges
Range up until:
a = [ "a", "b", "c", "d", "e", "f" ]
puts a[...-2].to_s
> ["a", "b", "c", "d"]
a = [ "a", "b", "c", "d", "e", "f" ]
puts a[..-2].to_s
> ["a", "b", "c", "d", "e"]
Range starts from:
a = [ "a", "b", "c", "d", "e", "f" ]
puts a[3..].to_s
> ["d", "e", "f"]
a = [ "a", "b", "c", "d", "e", "f" ]
puts a[0..].to_s
> ["a", "b", "c", "d", "e", "f"]
Other use cases:
# Example 1: Rails Active Record
Invoice.where(paid: false).where(expires_at: ..Time.current)
# Example 2: Get a substring
str = "Hello World"
puts str[..5]
> "Hello "
3) Hash shorthand
Ruby automatically assigns the value of a local variable to the hash key if the name matches.
name = "John"
age = 30
x = { name:, age: }
y = { name: name, age: age }
puts x == y
> true
4) Arguments Forwarding
Arguments can be forwarded by using triple dots.
def plus(a, b)
a + b
end
def plus_with_comment(comment, ...)
puts comment
puts plus(...)
end
plus_with_comment("Adding 1 and 2", 1, 2)
> Adding 1 and 2
> 3
5) Endless Method Definition
Ruby allows endless method definition.
# Normal, with end
def plus(a, b)
a + b
end
# Endless
def minus(a, b) = a - b
puts plus(1, 2)
puts minus(1, 2)
> 3
> -1