def foo=(bar) irb(main):0...">

In Ruby, how do I check if the "foo = ()" method is set?

In Ruby, I can define the foo = (bar) method:

irb(main):001:0> def foo=(bar) irb(main):002:1> p "foo=#{bar}" irb(main):003:1> end => nil 

Now I want to check if this has been determined,

 irb(main):004:0> defined?(foo=) SyntaxError: compile error (irb):4: syntax error, unexpected ')' from (irb):4 from :0 

What is the correct syntax to use here? I suppose there must be a way to avoid "foo =" so that it is parsed and correctly passed to a specific one? Operator.

+60
ruby syntax-error
Feb 27 2018-10-28T00-02-27
source share
2 answers

The problem is that the foo= method foo= intended for use in assignments. Can you use defined? as follows to find out what is going on:

 defined? self.foo=() #=> nil defined? self.foo = "bar" #=> nil def foo=(bar) end defined? self.foo=() #=> "assignment" defined? self.foo = "bar" #=> "assignment" 

Compare this to:

 def foo end defined? foo #=> "method" 

To check if the foo= method is set instead of respond_to? :

 respond_to? :foo= #=> false def foo=(bar) end respond_to? :foo= #=> true 
+102
Feb 27 '10 at 18:56
source share

Can you check if a method exists with the respond_to? method respond_to? , and you pass it a character, for example. bar.respond_to?(:foo=) to find out if the bar object has a foo= method. If you want to know if class instances respond to a method, can you use method_defined? for a class (or module), for example. Foo.method_defined?(:bar=) .

defined? It is not a method, but an operator that returns a description of the operand (or nil if it is not defined, so it can be used in an if statement). The operand can be any expression, that is, a constant, variable, purpose, method, method call, etc. The reason this doesn't work when you do defined?(foo=) is because of the parentheses, skip them and should work more or less as expected. defined? is a rather strange operator, and no one uses it to verify the existence of methods.

+31
Jun 04 '10 at 17:52
source share



All Articles