Ruby | String <=> Method

<=>() 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

0
1

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#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

chevron_right


Output:

-1



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.