Min-Soo Pipefeet
Min-Soo Pipefeet

Reputation: 2588

Is it possible to define own literals in Ruby?

For arbitrary-precision floating point decimal arithmetic in Ruby we can use the library BigDecimal. Unfortunately, compared to floats every explicitly given BigDecimal needs a lot of typing:

bd = BigDecimal("42.0")
# vs.
fl = 42.0

Is is possible to define own literals in Ruby?

So that for example the BigDecimal from above could be expressed like:

bd = 42°0

Or at least:

bd = %b(42.0)

Upvotes: 1

Views: 165

Answers (2)

Dorian
Dorian

Reputation: 23989

You could have:

def b(number)
  BigDecimal(number)
end

Then b(42.0) would work, pretty close to %b(42.0)

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369536

No, Ruby does not allow user-defined literals, overloading of literals, or any other similar thing.

Ruby does allow defining operator methods for existing operators, but not the definition of new operators, so even treating

42°0

as a binary operator ° will not work.

The closest you can get would be monkey-patching a ° method on Integer:

class Integer
  def °(decimal_part)
    BigDecimal("#{self}.#{decimal_part}")
  end
end

Upvotes: 1

Related Questions