Walker
Walker

Reputation: 5189

Ruby - Method Attributes

Is there any way to assign an attribute to a method? I know you can do it with classes, but I have a series of similar methods and it would really be helpful if I could assign each one an attribute. Does anyone know how to do it or if it is even possible in Ruby?

Edit: What I basically mean is that when you have a class you can assign attributes to it like this:

 class Person
  attr_accessor :age
  ...
 end

I'm wondering if it's also possible to do that with methods, like this:

class Trucks
 def get_fire_truck_name
   attr_accessor :size
   ...
 end
end

(Btw this is just an example. The actual program is much more complex which explains why I can't simply turn my methods into classes in order to give them attributes.)

Upvotes: 2

Views: 2738

Answers (2)

Brandan
Brandan

Reputation: 14983

Since methods are objects in Ruby, you can define methods on a Method object just as you would any other object. If you specifically want to use attr_accessor, you can open the method's eigenclass like this:

class Person
  attr_accessor :age
end

m = Person.instance_method(:age)
class << m
  attr_accessor :units
end

m.units = 'years'
puts m.units       #=> 'years'

You could also explicitly define the methods on the object using the def keyword:

def m.units
  @units || 'years'
end

def m.units=(u)
  @units = u
end

puts m.units
m.units = 'decades'
puts m.units

Upvotes: 2

engineerDave
engineerDave

Reputation: 3935

if you're just talking about being able to call methods as variables on an object there are at least three paths that I know of...

using an attr_reader accessor Accessors

attr_reader :your_cool_method_name

You can call send on the object. Note that this way ignores scope (public, protected, private)

@object.send :your_cool_mehod_name

Or you could do it through a method_missing call but this is a bit advanced and based on your question I would hold off on this approach until your familiarity with Ruby increases.

Upvotes: 0

Related Questions