Consider the following Ruby code snippet:
class Calculator
def add(a, b)
a + b
end
end
calc = Calculator.new
result = calc.send(:add, 5, 7)
puts resultWhat will be printed when this code runs?
class Calculator def add(a, b) a + b end end calc = Calculator.new result = calc.send(:add, 5, 7) puts result
Remember that send calls the method named by the symbol with given arguments.
The send method calls add with arguments 5 and 7, so it returns 12.
Look at this Ruby code:
class Secret
private
def whisper
"secret message"
end
end
s = Secret.new
puts s.send(:whisper)What will happen when this code runs?
class Secret private def whisper "secret message" end end s = Secret.new puts s.send(:whisper)
Does send allow calling private methods?
send can call private methods, so it prints "secret message".
Examine this Ruby code:
class Person
def greet(name)
"Hello, #{name}!"
end
end
p = Person.new
p.send(:greet)Why does this code raise an error?
class Person def greet(name) "Hello, #{name}!" end end p = Person.new p.send(:greet)
Check the method parameters and how send is called.
The method greet requires one argument, but send was called without any arguments, causing an ArgumentError.
Given this Ruby code:
class Repeater
def repeat(times)
result = []
times.times { result << yield }
result
end
end
r = Repeater.new
Which send call correctly invokes repeat with argument 3 and a block that returns "hi"?
How do you pass a block to a method called by send?
You can pass a block directly after the send call, like in option A.
Consider this Ruby code:
class Dynamic
def method_missing(name, *args)
"Called #{name} with #{args.join(", ")}"
end
end
d = Dynamic.new
puts d.send(:hello, 1, 2, 3)What will be printed?
class Dynamic def method_missing(name, *args) "Called #{name} with #{args.join(", ")}" end end d = Dynamic.new puts d.send(:hello, 1, 2, 3)
What happens when a method is missing and send is used?
The method_missing method catches calls to undefined methods, so it returns the formatted string.