Underscore
The underscore symbol (_
) is used in a few different contexts in Ruby.
Readable Number Notation
Glance at the following number real quick. How long does it take to figure out how big it is?
> 10000000
=> 10000000
We can make it easier for ourselves and future readers of our code with some underscores to separate the thousands.
> 10_000_000
=> 10000000
Implicit Positional Arguments in a Block
We can use _1
, _2
, etc. to refer to the first, second, etc. positional arguments in a block.
> def method_using_block(a, b)
yield(a, b) if block_given?
end
=> :method_using_block
> method_using_block(4,5) { _2 ** _1 }
=> 625
Unused Variable
This is purely a convention. If you have a positional argument for a method that you don't care about and won't use, you can indicate that it is unused with a leading underscore.
def method_with_unused_argument(_, b)
b
end
A practical example of this is from Noel Rappin's article on Keyword Arguments ↗ where the concept of a dual interface is introduced.
> def dual_interface(_name = nil, _state = nil, name: _name, state: _state)
p "#{name}: #{state}"
end
=> :dual_interface
> dual_interface("Taco", "Bell")
=> "Taco: Bell"
> dual_interface(name: "Taco", state: "Bell")
=> "Taco: Bell"
> dual_interface("Taco", state: "Bell")
=> "Taco: Bell"
> dual_interface()
=> ": "
Method and File Names
In Ruby, we snake_case all over the place.
- Methods names:
ActiveRecord::Base.sanitize_sql_array
- File names:
app/controllers/reading_statuses_controller.rb
Double Underscore Keywords
There are a few keywords ↗ in Ruby that use (double) underscores, such as __FILE__
and __LINE__
.
puts <<-`HEREDOC`
cat #{__FILE__}
HEREDOC
There is also the embedded data ↗ feature that relies on __END__
.