Basic question about << Float

Y

yc

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
 
R

Robert Klemme

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)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top