Ruby On Rails 面试题与答案
Question: How can you dynamically define a method body in Ruby on Rails?Answer:An instance method can be defined dynamically with Module#define_method(name, body), where name is the methods name given as a Symbol, and body is its body given as a Proc, Method, UnboundMethod, or block literal. This allows methods to be defined at runtime, in contrast to def which requires the method name and body to appear literally in the source code. class Conjure
def self.conjure(name, lamb)
define_method(name, lamb)
end
end
# Define a new instance method with a lambda as its body Conjure.conjure(:glark, ->{ (3..5).to_a * 2 })
Conjure.new.glark #=> [3, 4, 5, 3, 4, 5]
Module#define_method is a private method so must be called from within the class the method is being defined on. Alternatively, it can be invoked inside class_eval like so: Array.class_eval do
define_method(:second, ->{ self.[](1) })
end
[3, 4, 5].second #=> 4
Kernel#define_singleton_method is called with the same arguments as Module#define_method to define a singleton method on the receiver. File.define_singleton_method(:match) do |file, pattern|
File.read(file).match(pattern)
end
File.match('/etc/passwd',/root/) #=> #<MatchData "root"> |
保存以便复习
收藏此条目、标记为困难题,或将其加入复习集合。
用户评价最有帮助的内容:
- What is Ruby On Rails?
- Why Ruby on Rails?
- Explain how (almost) everything is an object in Ruby.
- What are Gems and which are some of your favorites?
- How would you declare and use a constructor in Ruby?