This is a method of creating a program that returns True when there are two variables "a = abc" and "b = HiAbc" and one of the strings a and b is at the end of the other string. In this case, abc of a exists in the last three characters of b, so it is True.
It can be created by using the following two methods.
--Downcase method to convert uppercase to lowercase
ruby
a = "AbC"
a_down = a.downcase
//This causes a_abc is entered in down
--Slice method if you want to cut out a character string at a specific position
ruby
a = "AbC"
a_slice = a.slice(1)
//This causes a_b is in slice
ruby
def compare(a, b)
a_down = a.downcase
b_down = b.downcase
a_len = a_down.length
b_len = b_down.length
if b_down.slice(-(a_len)..- 1) == a_down || a_down.slice(-(b_len)..- 1) == b_down
puts "True"
else
puts "False"
end
end
The 2nd to 5th lines define the variables to be used after this.
ruby
a_down = a.downcase //All the character strings of a are made lowercase and a_Substitute for down
b_down = b.downcase //All lowercase letters in b and a_Substitute for down
a_len = a_down.length // a_The length of the down string is a_Substitute for len
b_len = b_down.length // a_The length of the down string is a_Substitute for len
After that, it is judged by the following if statement.
ruby
if b_down.slice(-(a_len)..- 1) == a_down || a_down.slice(-(b_len)..- 1) == b_down
puts "True"
else
puts "False"
end
The Japanese translation of "b_down.slice (-(a_len) ..-1 == a_down" is "cut out 1 to a_len from the right of b_down".
Assuming that a_len is "3" and b_down is "hiabc", it will be "cut 1 to 3 characters from the right of hiabc". Then the cut character string becomes "abc".
Keep in mind that the slice method will calculate from the beginning if you pass a positive value, and from the end if you pass a negative value.
By using the operator "or" for the case of b_down and the condition of a_down, it is possible to check from both variables. (Honestly, when I first saw it, I couldn't translate it and was depressed.)
Recommended Posts