text
stringlengths
0
444
----
# bad
x == 0.1
x != 0.1
# good - using BigDecimal
x.to_d == 0.1.to_d
# good - not an actual float comparison
x == Float::INFINITY
# good
(x - 0.1).abs < Float::EPSILON
# good
tolerance = 0.0001
(x - 0.1).abs < tolerance
# Or some other epsilon based type of comparison:
# https://www.embeddeduse.com/2019/08/26/qt-compare-two-floats/
----
=== Exponential Notation [[exponential-notation]]
When using exponential notation for numbers, prefer using the normalized scientific notation, which uses a mantissa between 1 (inclusive) and 10 (exclusive). Omit the exponent altogether if it is zero.
The goal is to avoid confusion between powers of ten and exponential notation, as one quickly reading `10e7` could think it's 10 to the power of 7 (one then 7 zeroes) when it's actually 10 to the power of 8 (one then 8 zeroes). If you want 10 to the power of 7, you should do `1e7`.
|===
| power notation | exponential notation | output
| 10 ** 7 | 1e7 | 10000000
| 10 ** 6 | 1e6 | 1000000
| 10 ** 7 | 10e6 | 10000000
|===
One could favor the alternative engineering notation, in which the exponent must always be a multiple of 3 for easy conversion to the thousand / million / ... system.
[source,ruby]
----
# bad
10e6
0.3e4
11.7e5
3.14e0
# good
1e7
3e3
1.17e6
3.14
----
Alternative : engineering notation:
[source,ruby]
----
# bad
3.2e7
0.1e5
12e4
# good
1e6
17e6
0.98e9
----
== Strings
=== String Interpolation [[string-interpolation]]
Prefer string interpolation and string formatting to string concatenation:
[source,ruby]
----
# bad
email_with_name = user.name + ' <' + user.email + '>'
# good
email_with_name = "#{user.name} <#{user.email}>"
# good
email_with_name = format('%s <%s>', user.name, user.email)
----
=== Consistent String Literals [[consistent-string-literals]]
Adopt a consistent string literal quoting style.
There are two popular styles in the Ruby community, both of which are considered good - single quotes by default and double quotes by default.
NOTE: The string literals in this guide are using single quotes by default.
==== Single Quote [[consistent-string-literals-single-quote]]
Prefer single-quoted strings when you don't need string interpolation or special symbols such as `\t`, `\n`, `'`, etc.
[source,ruby]
----
# bad