Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 451
Alex Boisvert Avatar asked Feb 27 '10 18:02

Alex Boisvert


People also ask

How do you check if a method is defined in Ruby?

source_location will tell us the exact file name and line number that the method is defined. As the 'set' method comes from the Sinatra gem, it will output the path to the base. rb file from the gem, and the line number.

How do you define a method in Ruby?

Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name.

What is Foo in Ruby?

It just indicates a that it is a symbol instead of a string. In ruby, it is common to use symbols instead of strings. {:foo => value} {'foo' => value} It's basically a short-hand way of expressing a string. It can not contain spaces as you can imagine so symbols usually use underscores.

How do you call a method object in Ruby?

We call (or invoke) the method by typing its name and passing in arguments. You'll notice that there's a (words) after say in the method definition. This is what's called a parameter. Parameters are used when you have data outside of a method definition's scope, but you need access to it within the method definition.


1 Answers

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 
like image 166
molf Avatar answered Sep 22 '22 17:09

molf