Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby%20On%20Rails%20Interview%20Questions%20and%20Answers

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 method’s 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">
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook