Jus*_*ier 250 ruby operators comparison-operators spaceship-operator
什么是Ruby <=>(宇宙飞船)运营商?运营商是否通过其他语言实施?
Ton*_*rra 336
Perl可能是第一种使用它的语言.Groovy是另一种支持它的语言.基本上,而不是返回1(true)或0(false取决于参数是否相等或不相等),飞船运算符将返回1,0或者?1取决于相对于右参数左边参数的值.
a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return nil
Run Code Online (Sandbox Code Playgroud)
它对排序数组很有用.
ste*_*lag 67
当您在自己的类中定义并包含Comparable模块时,spaceship方法很有用.然后你的班级>, < , >=, <=, ==, and between?免费获得这些方法.
class Card
include Comparable
attr_reader :value
def initialize(value)
@value = value
end
def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other
self.value <=> other.value
end
end
a = Card.new(7)
b = Card.new(10)
c = Card.new(8)
puts a > b # false
puts c.between?(a,b) # true
# Array#sort uses <=> :
p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>]
Run Code Online (Sandbox Code Playgroud)
Ani*_*rya 15
我将用简单的例子来解释
[1,3,2] <=> [2,2,2]
Ruby将从左侧开始比较两个数组的每个元素.
1对于左数组小于2右数组.因此左数组小于右数组.输出将是-1.
[2,3,2] <=> [2,2,2]
如上所述,它将首先比较第一个相等的元素,然后比较第二个元素,在这种情况下,左数组的第二个元素更大,因此输出为1.
由于此运算符减少了与整数表达式的比较,因此它提供了基于多个列/属性对升序或降序进行排序的最通用方法。
例如,如果我有一个对象数组,我可以执行以下操作:
# `sort!` modifies array in place, avoids duplicating if it's large...
# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }
# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }
# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }
# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
8 * (a.zip <=> b.zip) +
-4 * (a.age <=> b.age) +
2 * (a.last <=> b.last) +
(a.first <=> b.first)
end
Run Code Online (Sandbox Code Playgroud)
这个基本模式可以概括为按任意数量的列排序,在每个列上以任何升序/降序排列。
| 归档时间: |
|
| 查看次数: |
93939 次 |
| 最近记录: |