I'm trying to do something like this in Ruby with the send
method:
class Foo
def bar
puts "Foo's bar method"
end
end
foo = Foo.new
foo.send :bar # => "Foo's bar method"
foo.send :baz # => NoMethodError: undefined method `baz' for #<Foo:0x00000000a2e720>
# Is there a way I can send :baz to foo without the program breaking?
# I.e., don't call anything if the given method doesn't exist.
Obviously, passing in the nonexistent :baz
returns an error, but I'm wondering if there's a way to call methods that do exist, in a send
-like way, and for methods passed in that don't exist, I'm just wanting the program not to break. Does anyone know of something that does that?
You can use method_missing
This will make your object to return
nil
in response to any undefined method.For more powerful way to implement kind of NullObject pattern take look at the naught gem by Avdi Grimm.