Basic question about << Float

Hi,
I am beginner in Ruby.
I wonder why the following doesn't work.

class << Float
  public
  def format(args)
    puts "self=#{self}"
    puts "args=#{args}"
    Kernel.format(args, self)
  end
end
puts 45.5678.format("%.02f")
Gives private method `format' called for 45.5678:Float (NoMethodError)

Thanks
yc

···

--
Posted via http://www.ruby-forum.com/.

You are defining a class instance method and trying to call an instance method. What you are really calling is this:

$ ruby -e 'p method(:format)'
#<Method: Object(Kernel)#format>

You would have to invoke your method as

Float.format(...)

However, given the fact that you can also do

$ ruby -e 'p "%.02f" % 1234'
"1234.00"

I don't see any reason why you would define the method you are trying to define. If you insist, you should do

irb(main):001:0> class Float
irb(main):002:1> def format(s) s % self end
irb(main):003:1> end
=> nil
irb(main):004:0> 1.234.format "%.02f"
=> "1.23"
irb(main):005:0> 1.0.format "%.02f"
=> "1.00"

Kind regards

  robert

···

On 21.04.2007 12:52, yc wrote:

Hi,
I am beginner in Ruby.
I wonder why the following doesn't work.

class << Float
  public
  def format(args)
    puts "self=#{self}"
    puts "args=#{args}"
    Kernel.format(args, self)
  end
end
puts 45.5678.format("%.02f")
Gives private method `format' called for 45.5678:Float (NoMethodError)