比较 ruby 中的两个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13824444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
comparing two strings in ruby
提问by Gandalf StormCrow
I've just started to learn ruby and this is probably very easy to solve. How do I compare two strings in Ruby?
我刚刚开始学习 ruby,这可能很容易解决。如何比较 Ruby 中的两个字符串?
I've tried the following :
我试过以下:
puts var1 == var2 //false, should be true (I think)
puts var1.eql?(var2) //false, should be true (I think)
When I try to echo them to console so I can compare values visually, I do this :
当我尝试将它们回显到控制台以便我可以直观地比较值时,我这样做:
puts var1 //prints "test content" without quotes
puts var2 //prints ["test content"] with quotes and braces
Ultimately are these different types of strings of how do I compare these two?
归根结底,这些不同类型的字符串如何比较这两者?
采纳答案by AShelly
From what you printed, it seems var2is an array containing one string. Or actually, it appears to hold the result of running .inspecton an array containing one string. It would be helpful to show how you are initializing them.
从您打印的内容来看,它似乎var2是一个包含一个字符串的数组。或者实际上,它似乎保存了.inspect在包含一个字符串的数组上运行的结果。展示您如何初始化它们会很有帮助。
irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]
回答by tokhi
Here are some:
这里有一些:
"Ali".eql? "Ali"
=> true
The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:
spaceship ( <=>) 方法可用于根据字母顺序比较两个字符串。如果字符串相同,<=> 方法返回 0,如果左侧字符串小于右侧字符串,则返回 -1,如果大于右侧字符串,则返回 1:
"Apples" <=> "Apples"
=> 0
"Apples" <=> "Pears"
=> -1
"Pears" <=> "Apples"
=> 1
A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:
可以使用 casecmp 方法执行不区分大小写的比较,该方法返回与上述 <=> 方法相同的值:
"Apples".casecmp "apples"
=> 0
回答by Zbigniew
var1is a regular string, whereas var2is an array, this is how you should compare (in this case):
var1是一个常规字符串,而var2是一个数组,这是您应该比较的方式(在这种情况下):
puts var1 == var2[0]
回答by p.matsinopoulos
Comparison of strings is very easy in Ruby:
在 Ruby 中比较字符串非常简单:
v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true
Make sure your var2 is not an array (which seems to be like)
确保您的 var2 不是数组(似乎是这样)

