如何计算字符

时间:2018-10-26 04:08:26

标签: ruby

我需要数一串中的桃子和茄子的数量,然后说出更多的数量。我尝试过:

def counting(eggplant_peaches)
  eggplants_counting = 0
  peaches_counting = 0
  (0..eggplant_peaches.length).each do |i|
    if eggplant_peaches[i] == 
      eggplants_counting = eggplants_counting + 1
    elsif eggplant_peaches[i] == 
      peaches_counting = peaches_counting + 1
    end
  end
  if eggplants_counting > peaches_counting
    puts “More ”
  elsif peaches_counting > eggplants_counting
    puts “More ”
  end
end

我得到一个错误:

undefined local variable or method '' for main:Object

我该如何计算代码并使代码少一点?

2 个答案:

答案 0 :(得分:3)

您的茄子和桃子必须用引号引起来,以使字符串正确,

if eggplant_peaches[i] == ""

现在,当您询问如何缩短代码长度时,您可以执行以下操作:

def counting(array)
  winner = array.group_by(&:itself).sort_by {|k,v| v.size }.last.first
  # The steps here are:
  # %w[  ].group_by(&:itself)
  #  => {""=>[""], ""=>["", ""]}
  # .sort_by { |k,v| v.size}
  #  => [["", [""]], ["", ["", ""]]]
  # .last
  #  => ["", ["", ""]]
  # .first
  #  => ""
  puts "More #{winner}"
end

counting(%w[  ])
 => More 

作为奖励,以上代码也适用于香蕉:

counting(%w[     ])
 => More 

答案 1 :(得分:3)

更快的方法(频率计数):

BitBlt

尽管您也可以在Marcin Kołodziej的决定中使用:max_by使其足够快:

array.each.with_object(Hash.new(0)) do |i, res|
  res[i] += 1
end.max_by(&:last).first