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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With