Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ruby have an identity function, i.e. x.fn == x, for all x?

Tags:

ruby

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.

like image 555
fearless_fool Avatar asked Oct 24 '13 06:10

fearless_fool


People also ask

When is a function considered to be an identity function?

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.

What is the identity function of R?

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.

How do you find the value of identity function?

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.

What is an identity relation in math?

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.


Video Answer


3 Answers

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
like image 141
Ajedi32 Avatar answered Oct 19 '22 21:10

Ajedi32


Your question is related to this one. It seems that now, Ruby is going to have #itself method.

like image 9
Boris Stitnicky Avatar answered Oct 19 '22 19:10

Boris Stitnicky


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.

like image 2
sawa Avatar answered Oct 19 '22 21:10

sawa