Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby On Rails Interview Questions and Answers

Ques. How can you dynamically define a method body in Ruby on Rails?

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)

# 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) })
[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.match('/etc/passwd',/root/) #=> #<MatchData "root">
Is it helpful? Yes No

Most helpful rated by users:

©2021 WithoutBook