我有一个像这样的案子:
约翰有120个糖果,他需要一些塑料袋,用这个数字标记每个塑料袋,并在每个袋子里放50个糖果。所以约翰只能装3个塑料袋:塑料袋1= 50糖果塑料袋2= 50糖果塑料袋3= 20糖果
我想从上面的案例中创建一个哈希。第一个变量是120个糖果,第二个变量是每个塑料袋50个糖果。我已经编写了一个方法来创建这样的哈希:
def make_a_hash(candies, each_candies)
mark_number = 1
arry = []
begin
put_candy = candies / each_candy > 0 ? each_candy : candies
candies = candies - put_candy
arry << [mark_number, put_candy]
mark_number += 1
end while candies > 0
arry.to_h
end
#=> make_a_hash(120, 50)
#=> {1=>50, 2=>50, 3=>20}这种方法正在起作用,我想知道是否有另一种最佳实践,而不是我的方法。
发布于 2017-05-16 14:23:31
我认为我们可以很容易地得到除法结果和使用divmod的余数。在此之后,我将构造带有完整组的数组,然后添加到它的最后一个组,如果它存在(提醒)。然后,只需创建一个哈希,并将索引作为数组中的键。
def in_groups_with_index(num, capacity)
full_groups, last_group_amount = num.divmod(capacity)
array = [capacity] * full_groups
array << last_group_amount if last_group_amount > 0
array.each_with_index.inject({}) do |hash, (element, index)|
hash.merge({(index+1) => element})
end
end方法实例:
in_groups_with_index(120, 50) # => {1=>50, 2=>50, 3=>20}
in_groups_with_index(0, 50) # => {}
in_groups_with_index(120, 0) # => divided by 0 exception对我来说,尝试把120种糖果装进不能携带任何糖果的袋子里是很奇怪的。但是,如果希望方法在这种情况下不抛出异常,则可以在方法的和方法或调用divmod的行中添加援救。
full_groups, last_group_amount = (num.divmod(capacity) rescue [0,0])
# or
full_groups, last_group_amount = num.divmod(capacity) rescue return {}
# or
def in_groups_with_index(num, capacity)
# ...
rescue
{}
endhttps://codereview.stackexchange.com/questions/157690
复制相似问题