在Ruby

时间:2016-05-30 13:25:45

标签: ruby-on-rails ruby

净启动子得分可以具有0-10的值。它分为三组:

发起人=得分为9或10分的受访者 Passives =受访者给出7或8分 批评者=受访者给出0到6分

分数计算为促销员和批评者百分​​比之间的差异。

我们说我们得分[10, 9, 10, 6, 2, 5, 10]

这将得分+14(57% - 43%)。

我希望我可以计算数组中某个范围的出现次数,如果有可能我会这样做

total_count = array.size
promoters = array.count(9..10)
passives = array.count(7..8)
detractors = array.count(0..6)

promoters_perc = promoters.to_f / total_count * 100
detractors_perc = detractors.to_f / total_count * 100

score = promoters_perc - detractors_perc

我该怎么做这个计算?

3 个答案:

答案 0 :(得分:3)

您可以使用哈希计算所有指标:

arr = [10, 9, 10, 6, 2, 5, 10]
count = arr.each_with_object(Hash.new(0)) do |e, memo|
  case e
  when 0..6 then memo[:detractors] += 1
  when 7..8 then memo[:passives] += 1
  when 9..10 then memo[:promoters] += 1 
  end
end

score = (count[:promoters] - count[:detractors]).to_f / arr.size * 100
=> 14.285714285714285

更短的解决方案:

metrics = { promoters: 9..10, passives: 7..8, detractors: 0..6 }
count = metrics.each {|k, v| metrics[k] = arr.count {|e| v === e}}

score = (count[:promoters] - count[:detractors]).to_f / arr.size * 100
=> 14.285714285714285

答案 1 :(得分:1)

还有其他一些方法可以做到这一点,但为简单起见,这应该有效。

array = [10, 9, 10, 6, 2, 5, 10]
total_count = array.size
promoters = array.count {|x| x > 8}
passives = array.count {|x| x > 6 && x <9}
detractors = array.count {|x| x < 7}

promoters_perc = promoters.to_f / total_count * 100
detractors_perc = detractors.to_f / total_count * 100

score = promoters_perc - detractors_perc

答案 2 :(得分:0)

这是另外一种方法,代码是自我解释的。

data = [10, 9, 10, 6, 2, 5, 10]

score_range = [promoters = (9..10), passives = (7..8), detractors = (0..6)]
#=> [9..10, 7..8, 0..6]
grouped = data.group_by {|i| score_range.select {|sr| sr.cover?(i)} }.to_h
#=> {[9..10]=>[10, 9, 10, 10], [0..6]=>[6, 2, 5]}
percentage = grouped.map {|(k),v| [k, (v.size  * 100.0/ data.size).round]}.to_h
#=> {9..10=>57, 0..6=>43}
nps = percentage[promoters] - percentage[detractors]
#=> 14