Skip to content
Related Articles

Related Articles

Improve Article

Ruby | String <=> Method

  • Last Updated : 07 Jan, 2020

<=>() is a String class method in Ruby which is used for comparisons of the strings. This method returns -1, 0, +1, or nil depending on whether the specified string is less than, equal to, or greater than 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.

Note: The longer string is considered greater than the shorter one if the specified strings are of different lengths, and the strings are equal when compared up to the shortest length,



Example 1:




#ruby 2.3.1 
     
# Ruby program to demonstrate
# the <=> method
     
# Taking a string and
# using the method
puts "Ruby" <=> "Ruby"
puts "Hello" <=> "Hell"

Output:

0
1

Example 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

Output:

-1

My Personal Notes arrow_drop_up
Recommended Articles
Page :