method_missing, as the name suggests, is called when the method cannot be found. With this powerful meta-programming tool, we can create dynamic methods, such as the dynamic finder in Active Record class Legislator Send is also a powerful tool for dynamic method invocation. Its function is to pass a method to the object in the form of parameters class Box def open_2 def open_3 def open_4 def open_5 box = Box.new box.send("open_#{num}")
# Pretend this is a real implementation
def find(conditions = {})
end
# Define on self, since it's a class method
def self.method_missing(method_sym, *arguments, &block)
# the first argument is a Symbol, so you need to_s it if you want to pattern match
if method_sym.to_s =~ /^find_by_(.*)$/
find($1.to_sym => arguments.first)
else
super
end
end
end
def open_1
puts "open box"
end
puts "open lock and open box"
end
puts "It's a open box"
end
puts "I can't open box"
end
puts "Oh shit box!"
end
end
What are some of your favorite gems? What are their alternatives?
What are #method_missing and #send? Why are they useful?
Ruby program to add two integer numbers
Ruby program to check whether the given number is Armstrong
Ruby program to generate random numbers
How to Sort Array in Ruby?
Ruby program to print Fibonacci series
What's the difference between a lambda, a block and a proc?
how to create an array with Array.[](*args) in Ruby ?
Creating Array with Array.new(size, obj) in Ruby
Ruby program to check whether the given number is palindrome
How to shuffle an array in Ruby?
Ruby program to Calculate the factorial of given number
What are the various Ruby runtimes, and how are they different?
How to create two dimensional array in ruby?
How to get index of array element in Ruby
Ruby program to reverse a string
Program to Print Triangle of Numbers in Ruby
Ruby program to print an array
How to add/remove elements to Array in Ruby?
Ruby program to check whether the given number is prime or not
How to Replace array elements in Ruby?
How to Get Input with Gets in Ruby