Any good reason for Ruby to have == AND eql ?? (similar to to_a and to_ary)

Do I know eql? used by hashes to see if the object matches the key *and you do

def ==(rb)

if you want to support the == operator, but there must be a good reason that hashes do not use == instead. Why is this? When will you have the definitions for == and eql? which are not equivalent (for example, one is an alias for the other)?

Similarly, why to_ary in addition to to_a?

This question arose in response to an answer that someone gave me to another question .

*Surely hash also assumes eql? == true means that the hash codes are equal.

Also, is it basically a terrible idea to redefine equal?

+3
source share
5 answers

I don’t know the arguments for this particular choice in ruby, but I’ll just point out that equality is a complex concept.

Common Lisp, for example, has eq, eql, equal, equalp and for this question =

It is very useful to be able to distinguish between two references to the same object, two different objects of the same type with the same value, two objects with the same value, but different types, etc. How many variations make sense depends on what makes sense in the language.

If I remember it correctly (I don't use ruby), rubys predicates implement three of these cases

== is the equality of value

EQL? is the equality of value and type

are equal? true only for the same object

+9
source

== checks if two values ​​are equal, and eql? checks if they are equal And of the same type.

irb(main):001:0> someint = 17
=> 17
irb(main):002:0> someint == 17
=> true
irb(main):003:0> someint.eql? 17
=> true
irb(main):004:0> someint.eql? 17.0
=> false
irb(main):005:0> someint == 17.0
=> true
irb(main):006:0>

, eql? , . 17.0, false, , someint .

+13

, to_a to_ary ( to_s to_str, to_i to_int) . ,

17.to_s

,

17.to_str

.

+3

, to_ary Hash (no to_a), Array to_a to_ary :

to_a:

. Array, Array.

to_ary:

.

0

, eql?, - to_a to_ary. Ruby duck-typing - . : foo (to_a). , to_a, to_s, to_i . , String , to_a. - : foo (to_ary). , , foo - String, foo - , , foo. "" . , , to_int. , , , - . , , - , , , , ++ reinterpet_cast<>. .

0

Source: https://habr.com/ru/post/1706766/


All Articles