Ruby uppercase only specified range

Introduction

This will be a learning note.

Two space-separated integers and a string are entered. The substring of the range of two integers is output in uppercase.

Input example 1
2 6
this is a pen

Output example 1
tHIS Is a pen
Input example 2
2 6
Welcome to the paiza! I`m studying ruby!

Output example 2
WELCOMe to the paiza! I`m studying ruby!

Source code

nums = gets.chomp.split(' ')
str = gets.chomp

(1..(str.size)).each do |i|
  if nums[0].to_i <= i && i <= nums[1].to_i
    print str[i - 1].upcase
  else
    print str[i - 1]
  end
end

Commentary

nums = gets.chomp.split(' ')
str = gets.chomp

gets method: Receives input as a "character string" line by line. chomp method: Removes line breaks in character strings. split method: Splits a character string into an array.

(1..(str.size)).each do |i|

From 1 to the size method, assign the character string of str to the i variable and repeat one by one. (13 times)

if nums[0].to_i <= i && i <= nums[1].to_i
    print str[i - 1].upcase
  else
    print str[i - 1]
  end

In the if statement, i (array number) is larger than nums [0](2 in Example 1) and i is larger than nums [1](6 in Example 1). If (array number) is small, convert it to uppercase with ʻupcase`.

Otherwise, output as it is.

Finally

The explanation may be a little difficult to understand. I would appreciate it if you could point out any mistakes.

Recommended Posts

Ruby uppercase only specified range
Uppercase only the specified range with substring. (How to use substring)
ruby Uppercase letters
Explanation about Ruby Range object