红宝石 |字符串 <=> 方法
<=>()是 Ruby 中的 String 类方法,用于比较字符串。此方法返回 -1、0、+1 或 nil,具体取决于指定字符串是小于、等于还是大于 other_string。
Syntax: str other_string
Parameters: Here, str and other_string are the strings which are compared.
Returns: Returns nil if the two specified values are incomparable.
注意:如果指定的字符串长度不同,则认为较长的字符串大于较短的字符串,并且与最短长度相比,字符串相等,
示例 1:
#ruby 2.3.1
# Ruby program to demonstrate
# the <=> method
# Taking a string and
# using the method
puts "Ruby" <=> "Ruby"
puts "Hello" <=> "Hell"
输出:
0
1
示例 2:
#ruby 2.3.1
# Ruby program to demonstrate
# the <=> method
# Taking a string and
# using the method
puts "ayucdef" <=> "ayucdefg"
# return nil for this
puts "Ruby" <=> 77
输出:
-1