I know send takes string or symbol with arguments while instance_eval takes string or block, and their difference could be apparent given receivers.
My question is what the 'under the hood' difference is for the example below?
1234.send 'to_s' # '1234'
1234.instance_eval 'to_s' # '1234'
Whatever you can do with
send
is a proper subset of that ofinstance_eval
. Namely, the argument tosend
has to be a single method (and its arguments), whereas the argument toinstance_method
is an arbitrary code. So whenever you havesend
, you can rewrite it withinstance_eval
, but not vice versa.However, performancewise,
send
is much faster thaninstance_eval
since there is no additional parsing required to executesend
, whereasinstance_eval
needs to parse the whole argument.In your example, the result will be the same, but the first one will run faster.
From the fine manual:
and for
instance_eval
:So
send
executes a method whereasinstance_eval
executes an arbitrary block of code (as a string or block) withself
set to the object that you're callinginstance_eval
on.In your case, there isn't much difference as the string you're handing to
instance_eval
is just a single method. The main difference is that anyone reading your code (including you in six months) will be wondering why you're usinginstance_eval
to call a single method.You might also be interested in
Object#public_send
andBasicObject#__send__