Ruby/String/String comparisons
Материал из Wiki.crossplatform.ru
Версия от 17:56, 13 сентября 2010; ViGOur (Обсуждение | вклад)
A case-insensitive comparison is possible with casecmp, which has the same possible results as <=> (-
"a" <=> "A" # => 1 "a".casecmp "A" # => 0
compare strings with the <=> method
It compares the character code values of the strings, returning -1 (less than), 0 (equals), or 1 (greater than), depending on the comparison, which is case-sensitive "a" <=> "a" # => 0 "a" <=> 97.chr # => 0 "a" <=> "b" # => -1 "a" <=> """ # => 1
Comparing Strings
You can do that with the == method. print "What was the question again?" if question == ""
Comparing With Regular Expressions
string = "This is a 30-character string." if string =~ /([0-9]+)-character/ and $1.to_i == string.length "Yes, there are #$1 characters in that string." end
perform "greater than" and "less than" comparisons:
puts "x" > "y" puts "y" > "x"
string contains lowercase characters
string = "This is a test" if string =~ /[a-z]/ puts "string contains lowercase characters" end
string contains mixed case
string = "This is a test" if string =~ /[A-Z]/ and string =~ /[a-z]/ puts "string contains mixed case" end
string contains uppercase characters
string = "this is a test" if string =~ /[A-Z]/ puts "string contains uppercase characters" end
string starts with a capital letter
string = "This is a test" if string[0..0] =~ /[A-Z]/ puts "string starts with a capital letter" end
Text Manipulation
letters = "abcde" puts letters =~ /a/ puts letters =~ /b/ puts letters =~ /e/ puts letters =~ /x/ letters = "abcde" puts letters =~ /aa?/ puts letters =~ /ax?/ letters = "abcde" puts letters =~ /ab?/ puts letters =~ /bc?/ puts letters =~ /b?/