Documenting several modern additions of the Ruby language syntax
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
gpt-4.1-2025-04-14
2025-05-17 19:04:44
This article highlights recent Ruby syntax enhancements, including new block parameter options, infinite ranges for arrays and substrings, hash shorthand for easier value assignment, argument forwarding with triple dots, and endless method definitions for concise function declarations. These features improve code readability and developer productivity in Ruby.
Chrome On-device AI
2025-06-19 02:35:18