简体   繁体   中英

When and how is it useful to dynamically add a method to a Ruby object?

I have been trying to learn Ruby from 'The Well-grounded Rubyist' and I came across the idea of adding methods to an object at run-time:

obj = Object.new
obj.respond_to? "hello" # Returns false

def obj.hello
  puts "something"
end

obj.respond_to? "hello" # Returns true
obj.hello()  # Output is "something"

I have a background in Python and Java, and I cannot imagine any way for me to use this new idea. So, how is this useful? How does it fit into the spirit of object-oriented programming? Is it expensive to do this at run-time?

There's always a long list of things you can do in any language but shouldn't do without a good reason and extending a single object is certainly high on that list.

Normally you wouldn't define individual methods, but you might include a bunch of them:

module Extensions
  def is_special?
    true
  end
end

obj = Object.new
obj.send(:extend, Extensions)

obj.is_special?
# => true

ActiveRecord from Rails does this to dynamically create methods for models based on whatever the schema is at the time the Rails instance is launched, so each column gets an associated method. This sort of dynamic programming can be used to make the code adapt seamlessly to a changing environment.

There's a lot of cases where you'll want to spell this out explicitly so your methods are well documented, but for cases where it doesn't matter and responding dynamically is better than maintaining two things, like schema and the associated methods in your code, then it could be the best option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM