LoginSignup
0
0

More than 3 years have passed since last update.

Ruby 文字列を切り取る

Last updated at Posted at 2020-10-13

はじめに

学習用のメモになります

スペース区切りの2つの整数と、文字列が入力されるので、2つの整数の範囲の部分文字列を出力してください。

入力例1
2 6
this is a pen

出力例1
his i
入力例2
2 6
Welcome to the paiza! I`m studying ruby!

出力例2
elcom

ソースコード

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

for i in (nums[0].to_i - 1)..(nums[1].to_i - 1)
     print str[i]
end

解説

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

入力された数字と文字列をnumsは出力範囲、strは文字列を分解してそれぞれ代入する

getsメソッド: 入力を一行ごとに「文字列」で受け取る。
chompメソッド: 文字列の改行を取り除く。
splitメソッド: 文字列を分解して配列にする。

for i in (nums[0].to_i - 1)..(nums[1].to_i - 1)

for文でnums[0]からnums[1]の範囲をそれぞれ整数に変換してi変数に代入する

print str[i]

strの文字列の中のi変数の範囲を出力する

最後に

もし間違っているところがありましたらご指摘していただけると幸いです。

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0