LoginSignup
0
0

More than 5 years have passed since last update.

Ruby|グループごとにカウントするサンプル

Posted at

はじめに

いま、内定者研修の講師を後輩くんと組んでやっています。課題を出しているのですが、やってみたら面白かったのでメモ程度ですが掲載します。

StackOverflowで「このプログラムどう?」とか聞くと質問の質が悪いとかでBANされるかもしれないのでQiitaにするとか口が裂けても言えない

課題

課題:0〜100点のテスト結果を区間ごとにカウントアップするプログラムを作成してください。カウントアップの出力例は次のとおりです。

  0点から 10点:*****
 11点から 20点:****
 21点から 30点:***
 31点から 40点:**********
 41点から 50点:******
 51点から 60点:***
 61点から 70点:****
 71点から 80点:****
 81点から 90点:*******
 91点から 99点:****
 91点から 99点:
100点から100点:

解答例

scores = Array.new(50){ rand(0..100) }

class ScoreRange
  def initialize(first, last = first)
    @range = Range.new(first, last)
    @count = 0
  end

  def in?(value)
    @range.include?(value)
  end

  def count_up
    @count += 1
  end

  def to_s
    "%3d点から%3d点:" % [@range.first, @range.last] + '*' * @count
  end
end

ranges = [
  ScoreRange.new(0, 10),
  ScoreRange.new(11, 20),
  ScoreRange.new(21, 30),
  ScoreRange.new(31, 40),
  ScoreRange.new(41, 50),
  ScoreRange.new(51, 60),
  ScoreRange.new(61, 70),
  ScoreRange.new(71, 80),
  ScoreRange.new(81, 90),
  ScoreRange.new(91, 99),
  ScoreRange.new(91, 99),
  ScoreRange.new(100)
]

scores.each do |score|
  match_range = ranges.detect{|range| range.in? score }
  match_range.count_up if match_range
end

puts ranges

Rangeだけでもかけると思いますが、区間にどれだけマッチしたかをカウントしたかったのでクラスを作成しました。後置if文はやや冗長ですが、、、、

0
0
4

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