[Ruby] Repeating arbitrary character strings

I am reviewing the drill to strengthen my logical thinking. As a beginner, I would appreciate it if you could let me know if you have any questions.

problem

Let's use the slice method to create a method that repeatedly outputs the last two characters of the string three times.

Output example:

extra_end ( 'Hello') → 'Chihachiwachi is' extra_end('qiita') → 'tatata' extra_end ('Sukiyaki') →'Yakiyaki'

Model answer

def extra_end(str)
  right_str = str.slice(-2, 2)  #①
  puts right_str * 3   #②
end

Commentary

① Get "the last two characters of the character string" The slice method can be retrieved from the last element of the string using minus. (-2, 2) means to get 2 characters counting from the second character from the back. And I'm assigning it to right_str.

② Repeat the acquired 2 characters 3 times



This time there was a condition "use the slice method" in the problem, but you can also get the last two characters without using it.
def extra_end(str)
  right_str = str[-2, 2]
  puts right_str * 3
end

Recommended Posts

[Ruby] Repeating arbitrary character strings
Display character strings character by character [Note]
[Java] Remove whitespace from character strings
[Algorithm] Descending order of character strings