私はInterview Cakeに関する質問をしており、新しい値を挿入すると計算が行われます。私の本能はゲッターメソッドにそのロジックを置くことでした。私はベストプラクティスに関するいくつかの洞察を期待していました。Rubyクラスの挿入メソッドまたはゲッターメソッド内で計算を行う必要がありますか?
その解決:私が最初に書いた
# Write a class TempTracker with these methods:
#
# insert()—records a new temperature
# getMax()—returns the highest temp we've seen so far
# getMin()—returns the lowest temp we've seen so far
# getMean()—returns the mean of all temps we've seen so far
# getMode()—returns a mode of all temps we've seen so far
class TempTracker
def initialize
# for mode
@occurrences = [0] * 111 # array of 0s at indices 0..110
@max_occurrences = 0
@mode = nil
# for mean
@total_numbers = 0
@total_sum = 0.0 # mean should be float
@mean = nil
# for min and max
@min_temp = nil
@max_temp = nil
end
def insert(temperature)
# for mode
@occurrences[temperature] += 1
if @occurrences[temperature] > @max_occurrences
@mode = temperature
@max_occurrences = @occurrences[temperature]
end
# for mean
@total_numbers += 1
@total_sum += temperature
@mean = @total_sum/@total_numbers
# for min and max
@max_temp = temperature if @max_temp.nil? || temperature > @max_temp
@min_temp = temperature if @min_temp.nil? || temperature < @min_temp
end
def get_max
@max_temp
end
def get_min
@min_temp
end
def get_mean
@mean
end
def get_mode
@mode
end
end
挿入とgetterメソッド:
は// ...
def insert(temp)
@max = temp if @max.nil? || @max < temp
@min = temp if @min.nil? || @min > temp
@total_sum += temp
@total_numbers += 1
@occurrences[temp] += 1
end
// ...
def get_mean
@total_sum/@total_numbers
end
def get_mode
@occurrences.each_with_index.max[1]
end
end
任意のヘルプの理解場合/ insertメソッドで計算ロジックを持つ理由は非常に参考になります!
アクセサーメソッドで「get」を含むRubyでは、お勧めできません。なぜ '@max.max'を[' max'](https://ruby-doc.org/core-2.4.1/Enumerable.html#method-i-max)を使ってしないのですか?これにより、これらのフィールドを最新の状態に保つ必要がなくなります。 – tadman