Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

syntax error - In Ruby, how do I check if method "foo=()" is defined?

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

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

Now I'd like to check if it has been defined,

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

What is the proper syntax to use here? I assume there must be a way to escape "foo=" such that it is parsed and passed correctly to the defined? operator.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that the foo= method is designed to be used in assignments. You can use defined? in the following way to see what's 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 that to:

def foo
end

defined?(foo)
#=> "method"

To test if the foo= method is defined, you should use respond_to? instead:

respond_to?(:foo=)
#=> false

def foo=(bar)
end

respond_to?(:foo=)
#=> true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...