Amit Erandole
Amit Erandole

Reputation: 12281

The un-googleable ruby's method method

There is apparently a ruby method called method and I can't find any docs or examples on it so far. Could someone please post a few useful annotated examples?

Upvotes: 2

Views: 188

Answers (5)

Julik
Julik

Reputation: 7856

One of the best uses of the bound method object returned by Object#method is for blocks. The return result of that method can be converted to a block argument. Imagine you have:

class Converter
  def convert_item(item)
    item.transmorph
  end
end

Then you could do this

c = Converter.new
elements.map(&c.method(:convert_item))

or when you are within the convertor

elements.map(&method(:convert_item))

which IMO is more elegant than the explicit block creation syntax. It also supports to_proc so you can do this

some_object.callback = my_handler.method(:activate).to_proc

and then in some_object you can do

@callback.call(data)

Upvotes: 1

ohnoes
ohnoes

Reputation: 31

I've mostly used it to look up source location of a specific method. (example run in irb on ruby-1.9.2-p290)

class Thing
  def foo
  end
end

Thing.new.method(:foo).source_location
=> ["(irb)", 2]

Thing.new.method(:foo).owner
=> Thing 

Upvotes: 3

d11wtq
d11wtq

Reputation: 35318

It's part of Object and is documented here:

http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-method

The class Method is documented here, and gives some examples:

http://www.ruby-doc.org/core-1.9.3/Method.html

Upvotes: 2

ZelluX
ZelluX

Reputation: 72675

Object#method, is this what you are looking for?

http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-method

Upvotes: 2

Milan Jaric
Milan Jaric

Reputation: 5646

there is docs about that method in ruby api documentation

http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-method

there is also method_defined? which could be also useful if you need method it self

http://www.ruby-doc.org/core-1.9.3/Module.html#method-i-method_defined-3F

Upvotes: 6

Related Questions