0

.<digit> means to interpret the number as a float instead of an integer.

Can I override .<digit> to let it point the index in an array so that the following will work?

c = [1, 2, 3, 4, 5, 6]
c.0 # => 1
c.3 # => 4
Ilya
  • 13,337
  • 5
  • 37
  • 53
Eduard Florinescu
  • 16,747
  • 28
  • 113
  • 179

3 Answers3

2

No. A method name can't begin with a number in Ruby. More about Ruby method names restrictions here.

Community
  • 1
  • 1
Ilya
  • 13,337
  • 5
  • 37
  • 53
2

No you can't. That is part of the literal expression for floats. It is not a method call. It is not done at Ruby syntax level.

sawa
  • 165,429
  • 45
  • 277
  • 381
0

As the other answers already told, it is not possible to override the number as method, but you can use parenthesis for an empty method.

class Array
  def method_missing(m ,*args, &block)
    # m will be 'call'
    self[args[0]] if args[0].is_a?(Fixnum)
  end
end


irb(main):009:0> [1,2,3,4,5].(0)
=> 1
irb(main):010:0> [1,2,3,4,5].(2)
=> 3
AlexN
  • 1,613
  • 8
  • 21