Sometimes when I'm passing a method name as an argument, I find myself wishing for an identity function such that any_obj.send(:identity) == any_obj
, so instead of this:
(transform.nil?) ? my_obj : my_obj.send(transform)
I could just write
my_obj.send(transform || :identity)
(This is a bit of a contrived example -- an identity function could do more than save a few keystrokes in more complicated examples.)
It would be easy enough to open up the definition of Object and add it, but is there something already there that I've overlooked? Does anyone else want this as well?
P.S.: I know my example should really be stated any_obj.send(:identity).equal?(any_obj)
, but sometimes pedantry obscures the question.
A function is considered to be an identity function when it returns the same value as the output that was used as its input. Let's go ahead and learn the definition of an identity function. An identity function is a function where each element in a set B gives the image of itself as the same element i.e., g (b) = b ∀ b ∈ B.
Let R be the set of real numbers. Thus, the real-valued function f : R → R by y = f (a) = a for all a ∈ R, is called the identity function. Here the domain and range (codomain) of function f are R.
An identity function is generally represented as f (a) = a. In this function, the value of the output and the argument used in the function are the same i.e. ‘a’. The graph of an identity function is generally a straight line passing through the origin.
It is also called an identity relation or identity map or identity transformation. If f is a function, then identity relation for argument x is represented as f (x) = x, for all values of x. In terms of relations and functions, this function f: P → P defined by b = f (a) = a for each a ϵ P, where P is the set of real numbers.
Yes. You're looking for Object#itself
, which is available in Ruby 2.2+.
From the docs:
itself → an_object
Returns obj.
string = 'my string' #=> "my string" string.itself.object_id == string.object_id #=> true
Your question is related to this one. It seems that now, Ruby is going to have #itself
method.
There is not any for now, but Matz has expressed an opinion favoring such method to be implemented: https://bugs.ruby-lang.org/issues/6373. It is likely to be implemented in future versions of Ruby.
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