Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

てぃーびーの Ruby 練習帳 | 連番を含む文字列を生成する

概要

連番を含む文字列を生成する

前提

この記事は、非エンジニアさんも含めた初心者向けです。

状況

連番を含む定型文字列をタイプする必要があるが、手動で行うのが面倒

サンプルデータ

以下のような文字列が欲しい時

書籍 Ruby 練習帳,1章,500 円
書籍 Ruby 練習帳,2章,500 円
書籍 Ruby 練習帳,3章,500 円
書籍 Ruby 練習帳,4章,500 円
書籍 Ruby 練習帳,5章,500 円
書籍 Ruby 練習帳,6章,500 円

解法一覧

Level 0

全て手動で入力する。

Level 1

1 行手動で入力し、 2-6 章分をコピーしてから 数値部分のみ手動で修正

Level 2

以下の Ruby のプログラムを作成し、結果を利用する。

  • generate_sequential_number_text.rb
(1..6).each { |i|
  puts "書籍 Ruby 練習帳,#{i}章,500 円"
}
  • 出力
% ruby generate_sequential_number_text.rb
書籍 Ruby 練習帳,1章,500 円
書籍 Ruby 練習帳,2章,500 円
書籍 Ruby 練習帳,3章,500 円
書籍 Ruby 練習帳,4章,500 円
書籍 Ruby 練習帳,5章,500 円
書籍 Ruby 練習帳,6章,500 円

応用

サンプルデータ

以下のような文字列を入力したい時

書籍 Ruby 練習帳,1章,500 円
書籍 Ruby 練習帳,3章,500 円
書籍 Ruby 練習帳,5章,500 円
書籍 Ruby 練習帳,7章,500 円

プログラム

  • generate_sequential_number_text_step.rb
1.step(7, 2).each { |i|
  puts "書籍 Ruby 練習帳,#{i}章,500 円"
}

出力

% ruby generate_sequential_number_text_step.rb
書籍 Ruby 練習帳,1章,500 円
書籍 Ruby 練習帳,3章,500 円
書籍 Ruby 練習帳,5章,500 円
書籍 Ruby 練習帳,7章,500 円

親記事