1

The following code uses:

send("#{duck1}=", true) 

and I tried the following code instead and was wondering why it didn't work:

duck1.send(=,true) 

Terminal shows: syntax error, unexpected '=', expecting ')'

2 Answers 2

2

Before we even get into the valid argument types for the send method, take a look at the error message. It's telling you that it's a syntax error to have a "bare" equals sign immediately after that opening parenthesis. So, right off the bat, you know that something is very wrong.

Now, if you take a closer look at the call that does work, you'll see that you're passing the string "something=", not a "bare" equals sign. That has a chance of working, based on the types of arguments that send takes.

If you read the documentation for send, you'll see that the first argument can be either a string or a symbol. "#{duck1}=" will be interpolated to be a string, so that's valid.

Now, the question becomes, "what is duck1, and will "#{duck1}=" be interpolated to the name of an existing function? I can't answer that, it completely depends on the value of duck1.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your input! So it seems like #send only takes symbol or string and interprets it as a method to do evaluation. And in this case, to get "#{duck1}=" to work, we also need to have attr_accessor :)
0

The first argument of send must be a symbol or a string representing a method name. = is not a symbol or a string. It is not even an object. Furthermore, even if you do send(:"=", ...) or send("=", ...), it will not work unless you have defined = as a method in a non-usual way. (Edited following Bob Gilmore and Jörg W Mittag's comments)

8 Comments

So "#{duck1}=" is a method and "=" is not. Is that correct?
Awesome! Thank you so much for your detailed explanation. Really appreciate it. method#send is so powerful yet elusive, and I find the official document not very helpful on explaining how to use it. Thanks again!
The first argument to send can also be a string.
@BobGilmore Forgot to mention that. Thanks.
"there is no such method as =" – define_method(:'=') do puts 'Hello' end; send(:'=') # Hello
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.