text
stringlengths 0
444
|
|---|
# bad
|
obj.yield_self { |x| x.do_something }
|
# good
|
obj.then { |x| x.do_something }
|
----
|
NOTE: You can read more about the rationale behind this guideline https://bugs.ruby-lang.org/issues/14594[here].
|
== Numbers
|
=== Underscores in Numerics [[underscores-in-numerics]]
|
Add underscores to large numeric literals to improve their readability.
|
[source,ruby]
|
----
|
# bad - how many 0s are there?
|
num = 1000000
|
# good - much easier to parse for the human brain
|
num = 1_000_000
|
----
|
=== Numeric Literal Prefixes [[numeric-literal-prefixes]]
|
Prefer lowercase letters for numeric literal prefixes.
|
`0o` for octal, `0x` for hexadecimal and `0b` for binary.
|
Do not use `0d` prefix for decimal literals.
|
[source,ruby]
|
----
|
# bad
|
num = 01234
|
num = 0O1234
|
num = 0X12AB
|
num = 0B10101
|
num = 0D1234
|
num = 0d1234
|
# good - easier to separate digits from the prefix
|
num = 0o1234
|
num = 0x12AB
|
num = 0b10101
|
num = 1234
|
----
|
=== Integer Type Checking [[integer-type-checking]]
|
Use `Integer` to check the type of an integer number.
|
Since `Fixnum` is platform-dependent, checking against it will return different results on 32-bit and 64-bit machines.
|
[source,ruby]
|
----
|
timestamp = Time.now.to_i
|
# bad
|
timestamp.is_a?(Fixnum)
|
timestamp.is_a?(Bignum)
|
# good
|
timestamp.is_a?(Integer)
|
----
|
=== Random Numbers [[random-numbers]]
|
Prefer to use ranges when generating random numbers instead of integers with offsets, since it clearly states your intentions.
|
Imagine simulating a roll of a dice:
|
[source,ruby]
|
----
|
# bad
|
rand(6) + 1
|
# good
|
rand(1..6)
|
----
|
=== Float Division [[float-division]]
|
When performing float-division on two integers, either use `fdiv` or convert one-side integer to float.
|
[source,ruby]
|
----
|
# bad
|
a.to_f / b.to_f
|
# good
|
a.to_f / b
|
a / b.to_f
|
a.fdiv(b)
|
----
|
=== Float Comparison [[float-comparison]]
|
Avoid (in)equality comparisons of floats as they are unreliable.
|
Floating point values are inherently inaccurate, and comparing them for exact equality is almost never the desired semantics. Comparison via the `==/!=` operators checks floating-point value representation to be exactly the same, which is very unlikely if you perform any arithmetic operations involving precision loss.
|
[source,ruby]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.