简体   繁体   中英

Ruby's comparator <=> Vs. Java's .equals; to compare Strings

Her is my ruby script:

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

puts books.sort! {

  |firstBook, secondBook|

  firstBook <=> secondBook

}

I was expecting it would print -1,0 or 1, but it prints book's name. How to get their boolean value in console.

Similarly in Java my code is:

public class sampletest {

    public static void main(String[] args) {
        String String1 = "hello";
        String String2 = "Hello";

        System.out.println(String1.equals(String2));
    }
}

Here output is: True (a Boolean value) I am new to Ruby, I don't understand the difference between these two

In the first example, you sort (involving lots of comparisons that you don't get to see). In the second example, you just compare. The Ruby equivalent of your Java snippet is:

string1 = "hello"
string2 = "Hello"
puts(string1 == string2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM