6

抱歉,如果重复(我没找到)

这只是为了确认 Ruby 的运算符==总是执行相等比较。IE

a == b

将 a 的值与 b 的值进行比较,而不是像 Java 那样,它们是否指向内存中的同一个对象(对于后者,在 Ruby 中,您应该使用a.object_id == b.object_id)。

因此,在 Ruby 中将字符串值与 == 进行比较是安全的(而在 Java 中这样做并不安全)

谢谢

编辑

问题在于任何 Ruby 对象的默认 == 行为,因为它可能误导 Java-C-C++ 程序员,假设 a==b 比较引用本身,而不是引用内容。

无论如何,您可以使用字符串查看此代码

one="hello"
two="he"
two << "llo"

if one == two
  puts "surprise: comparing values, not like in Java"
end

if not one.object_id == two.object_id
  puts "obvious: do this to compare references"
end

编辑 2

所以,在 Ruby 中,比较

a == b

检查 a 和 b 的值

但是,任务

a = b

不复制值,而是使 a 和 b 指向同一个对象!

继续前面的代码

puts one.object_id
puts two.object_id

puts " and now "

one = two

puts one.object_id
puts two.object_id
4

3 回答 3

3

In Ruby, == can be overloaded, so it could do anything the designer of the class you're comparing wants it to do. In that respect, it's very similar to Java's equals() method.

The convention is for == to do value comparison, and most classes follow that convention, String included. So you're right, using == for comparing strings will do the expected thing.

The convention is for equal? to do reference comparison, so your test a.object_id == b.object_id could also be written a.equal?(b). (The equal? method could be defined to do something nonstandard, but then again, so can object_id!)

(Side note: when you find yourself comparing strings in Ruby, you often should have been using symbols instead.)

于 2012-09-15T08:34:27.130 回答
1

From http://www.skorks.com/2009/09/ruby-equality-and-object-comparison/.

The code:

class MyObject
end
object1 = MyObject.new
object2 = object1
object3 = MyObject.new

puts "Object 1 is == to object 2: #{object1 == object2}"
puts "Object 1 is eql? to object 2: #{object1.eql? object2}"
puts "Object 1 is equal? to object 2: #{object1.equal? object2}"
puts "Object 1 is == to object 3: #{object1 == object3}"
puts "Object 1 is eql? to object 3: #{object1.eql? object3}"
puts "Object 1 is equal? to object 3: #{object1.equal? object3}"

The output:

Object 1 is == to object 2: true
Object 1 is eql? to object 2: true
Object 1 is equal? to object 2: true
Object 1 is == to object 3: false
Object 1 is eql? to object 3: false
Object 1 is equal? to object 3: false

Edit - Additional output:

irb(main):001:0> class MyObject
irb(main):002:1> end
=> nil
irb(main):003:0> object1 = MyObject.new
=> #<MyObject:0x281bc08>
irb(main):006:0> object1.respond_to?( '=='.to_sym )
=> true
irb(main):007:0> object1.respond_to?( 'eql?'.to_sym )
=> true
irb(main):013:0> MyObject.superclass
=> Object
于 2012-09-15T08:35:08.870 回答
0

根据“Ruby 编程语言”(Flanagan & Matsumoto),第 4.6.7 节第 106 页

== 是相等运算符。它根据左侧操作数的“相等”定义确定两个值是否相等。

在 3.8.3 第 74 页中:

每个对象都有一个对象标识符,一个 Fixnum,您可以使用 object_id 方法获得它。此方法返回的值在对象的生命周期内是常量且唯一的。

因此,这与 Java 正好相反(令我惊讶)。

于 2012-09-15T10:36:37.720 回答