Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Tags:

ruby

I always do this to test string equality in Ruby:

if mystring.eql?(yourstring)  puts "same" else  puts "different" end 

Is this is the correct way to do this without testing object equality?

I'm looking for the most concise way to test strings based on their content.

With the parentheses and question mark, this seems a little clunky.

like image 546
Bryan Locke Avatar asked Nov 10 '09 19:11

Bryan Locke


People also ask

What is the correct way of checking string equality?

You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

How do you check if a string is equality in Ruby?

Two strings or boolean values, are equal if they both have the same length and value. In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.

Are identical symbols the same in Ruby?

Symbols are immutable: Their value remains constant. Multiple uses of the same symbol have the same object ID and are the same object compared to string which will be a different object with unique object ID, everytime.


1 Answers

According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison

Doing either

mystring == yourstring

or

mystring.eql? yourstring

Are equivalent.

like image 121
JasonWyatt Avatar answered Sep 22 '22 14:09

JasonWyatt