RとRubyによるデータ開発入門という本の中にあるコードなのですがコードの意味がわからない部分があるので教えて下さい。
コード2の9行目のコードで Person.population << Person.new(frequency,use_duration)
という部分があるのですが
このコードの 「 Person.population 」はクラスメソッドなのでしょうか?
また「 << 」は何の役割を果たしているのでしょうか?
あとコード1のPersonクラスのクラス変数で@@populationも何の役割を果たしているのか理解できません。
どうか皆様のお力をお貸しください。
コード1
DURATION = 9 * 60 class Restroom attr_reader :queue #従業員の待ち行列 attr_reader :facilities #トイレ内の設備の数 def initialize(facilities_per_restroom = 3) #デフォルト値3 @queue = [] @facilities = [] facilities_per_restroom.times{@facilities << Facilitie.new} end def enter(person) unoccupied_facility = @facilities.find{|facility| not facility.occupied?} if unoccupied_facility unoccupied_facility.occupy person else @queue << person Person.population.delete person end end def tick @facilities.each { |f| f.tick} end end class Facility def initialize @occupier = nil #占有者 @duration = 0 #どれくらいの時間設備が使用されているか end def occupy(person) unless occupied? @occupier = Person @duration = 1 Person.population.delete person true else false end end def occupied? not @occupier.nil? end def vacate Person.population << @occupier @occupier = nil end def tick if occupied? and @duration > @occupier.use_duration vacate @duration = 0 elsif occupied? @duration += 1 end end end class Person @@population = [] attr_reader :use_duration attr_accessor :frequency def initialize(frequency = 4,use_duration = 1) @frequency = frequency @use_duration = use_duration end def self.population @@popuration end def need_to_go? rand(DURATION) + 1 <= @frequency end end 0. 番号リスト
コード2
require
1require './restroom' 2frequency = 3 3facilities_per_restroom = 3 4use_duration = 1 5population_range = 10..600 6 7data = {} 8population_range.step(10).each do |population_size| 9 Person.population.clear 10 population_size.times {Person.population << Person.new(frequency,use_duration)} 11 data[population_size] = [] 12 restroom = Restroom.new facilities_per_restroom 13 14 DURATION.times do |t| 15 data[population_size] << restroom.queue.size 16 queue = restroom.queue.clone 17 restroom.queue.clear 18 19 until queue.enpty? 20 restroom.enter person 21 end 22 23 Person.population.each do |person| 24 if person.need_to_go? 25 restroom.enter person 26 end 27 end 28 restroom.tick 29 end 30end 31 32CSV.open('simulation1.csv','w') do |csv| 33 lbl = [] 34 population_range.step(10).each {|population_size| lbl << population_size} 35 csv << lbl 36 DURATION.times do |t| 37 row = [] 38 population_range.step(10).each do |population_size| 39 row << data[population_size][t] 40 end 41 csv << row 42 end 43end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。