LoginSignup
0
0

More than 5 years have passed since last update.

僕も松江Ruby会議06で出された問題を(チカラ技で)解いてみた (;´Д`)

Last updated at Posted at 2015-12-05

元記事

僕も松江Ruby会議06で出された問題を解いてみた

無理矢理な回答です (;´Д)
print_csvが特にキモい (;´Д
)

ookiri.csv
name,ruby,php,python,perl
一郎,100,40,70,80
二郎,60,90,80,10
三郎,90,60,60,60
四郎,80,70,70,80
require 'csv'

class Ookiri
  attr_reader :ookiri, :lang, :lang_array, :attendances, :attendances_num, :lang_num, :switch

  def initialize(args={})
    @ookiri = CSV.table('ookiri.csv', headers:true, converters: :numeric, header_converters: :symbol)
    @lang = args[:lang] || ""
    @lang_array = ookiri.headers[1..-1]
    @lang_num = lang_array.length.to_f
    @attendances = ookiri[:name]
    @attendances_num = attendances.length - 1
    @switch = args[:switch] || ""
  end

  def print_csv
    if switch == "average"
      puts "average"
      hash_printer(average_hash)
    end
    if switch == "score"
      puts lang
      hash_printer(make_hash)
    end
  end

  def hash_printer(hash)
    sort_hash(hash).each{|k, v|  puts "#{k}, #{v}"}
    puts "-------------------------------"
  end


  def average_hash
    Hash[attendances.zip(score_total)]
  end

  def score_total
    (0..attendances_num).to_a.map{|num| get_average(num)}
  end

  def sort_hash(hash)
    hash.sort_by{|k, v| -v}.to_h
  end

  def score_by_language(num)
    lang_array.map{|lan| ookiri[num][lan]}
  end

  def get_average(num)
    score_by_language(num).inject{|k, v| k + v} / lang_num
  end

  def make_hash
    Hash[attendances.zip(ookiri[:"#{lang}"])]
  end
end
Ookiri.new(lang: "ruby", switch: "score").print_csv
Ookiri.new(lang: "python", switch: "score").print_csv
Ookiri.new(lang: "perl", switch: "score").print_csv
Ookiri.new(lang: "php", switch: "score").print_csv

Ookiri.new(switch: "average").print_csv

列や行が追加されたり削除されても多分大丈夫。

0
0
0

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