Without Book Interview Questions and Answers | Online Test | Moct Test
Download Android App in your Android Device from Google Play Store
- Search for "Withoutbook Practice Exam Test" in Mobile/Tablet Play Store
Institute Training Search by Name or Email

Exams Attended

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?
Ans.

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:

©2016 WithoutBook