The ** slice ** code came out as an answer with a Ruby drill, and I couldn't understand it easily, so I will leave it as a memorandum.
There are any two strings. Ignore case and select ** True ** if one character is at the end of the other If not, create a program that outputs ** False **. (That is, it is not case sensitive).
Ruby
def end_other(a,b)
a_down = a.downcase
b_down = b.downcase
a_len = a_down.length
b_len = b_down.length
if a_down.slice!(-(b_len)..a_len - 1) == b_down #← I will explain this line!
puts "True"
else
puts "False"
end
end
puts "Please enter the alphabet"
code = gets.chomp
puts "Please enter the characters you specify"
find_word = gets.chomp
end_other(code, find_word)
** slice ** returns the substring after removing the specified range from the string. Was: grin: Reference: https://docs.ruby-lang.org/ja/2.3.0/method/String/i/slice=21.html
Example
string = "this is a string"
string.slice!(2) #=> "i"
string.slice!(3..6) #=> " is "
string.slice!(/s.*t/) #=> "sa st"
string.slice!("r") #=> "r"
: warning: Count starts from ** 0 (zero) **! I stumbled here: sweat:
Therefore, the above answer can be explained in detail as follows: point_up:
Commentary
def end_other(a,b)
a_down = a.downcase
#Convert all letters of variable a to lowercase!
b_down = b.downcase
#Convert all letters of variable b to lowercase!
a_len = a_down.length
#Get the number of characters in variable a!
b_len = b_down.length
#Get the number of characters in variable b!
if a_down.slice!(-(b_len)..a_len - 1) == b_down
#-(b_len) :Returns the number of characters from the last character of variable a to the number of characters of variable b
#a_len - 1 :Returns the last character of the variable a
#.. :Above, represents the following
#abridgement
It looks like this, but honestly, even myself? ?? ?? So I will actually apply the characters: grinning:
Commentary commentary www
a = wOrD
b = Rd
def end_other(a,b)
a_down = a.downcase
#wOrD ⇒ word
b_down = b.downcase
#Rd ⇒ rd
a_len = a_down.length
#4 characters
b_len = b_down.length
#2 letters
if a_down.slice!(-(b_len)..a_len - 1) == b_down
#-(b_len) :Returns the last two characters of word ...>is r
#a_len - 1 :Returns the last character of word ...>d
#a_down.slice!(-(b_len)..a_len - 1) :Will be rd
#abridgement
It may be a little confusing. .. .. .. Sorry for my lack of writing: bow:
I hope it helps you a little: laughing:
Recommended Posts