繁体   English   中英

Ruby将hash中的相同元素数组或值组合在一起,

[英]Ruby same element array or value in hash , unite it,

今天,我的上级有一个非常艰巨的任务(也许仅对我来说这很困难)。

任务是这样的:

  1. 他给了我几个字符串数据(准确地说是8个字符串数据)。 我可以选择将其存储在数组或哈希中。

     "hello", "you", "great", "you", "great", "hello", "great", "great" 
  2. 现在,我必须合并那些字符串中的相同数据。 我的意思是如果我将它们放在数组中。

     myary = ["hello", "you", "great", "you", "great", "hello", "great", "great"] 

    我必须让它变成这样

     myary = ["hello x2", "you x2', great x4"] # I need to append "x" and a variable indicating the total sum of every same string in the array. 

    我可以根据需要使用哈希,但是问题是,我找不到一种很好的方法来执行此操作。 我奋斗了几个小时,徒劳无功。 我能做的最好的是在这里:

我将它们存储在哈希中。

myhash = {

1 => "hello",
2 =>  "you",
3 => "great",
4 => "you",
5 => "great",
6 => "hello",
7 => "great",
8 => "great",
 }

然后我写这段代码:

 myarray = []

@variable = 0
for i in 1..myhash.length
  for j in 1..myhash.length
    @variable += 1 if myhash[i] == myhash[j]
  end
  myarray[i] = myhash[i]  << " x#{@variable}"
 @variable = 0
end

puts myarray

这将给出输出:

hello x2    # This nice "hello" is 2 
you x2      # This good "you" indeed is 2
great x4    # This perfect "great" is 4          <= Everything great 'till here. But...
you x1      # Why?        
great x3    # What the..?
hello x1    # Oh c'mon..
great x2    # Okay, I'm screwed
great x1    # Stackoverflow help me!!

如您所见,我很困惑,我知道代码是错误的,但是相信我,我几乎把头撞在墙上,因为这很重要。 请有人,我需要认真的帮助。 哦,我想确定一些事情,这个任务有可能完成吗? 我只是想确保我的上级不让我忙于这项任务。 但实际上我想知道这是否真的可能。 抱歉,我做错了什么。 非常感谢你。 请不要大怒:)毕竟,我只是问,如果您觉得自己不想给出答案,请直接离开。 肯定的回答非常赞赏。

您几乎不需要在ruby中使用低级的for循环。

myary = ["hello", "you", "great", "you", "great", "hello", "great", "great"]

myary.group_by{|el| el }.map {|key, items| "#{key} x#{items.length}"} # => ["hello x2", "you x2", "great x4"]

文档: Enumerable#group_byEnumerable#map

您还可以使用哈希,其中的键是单词,值是您看到它的次数。 第一次看到一个单词时,将其添加到哈希中,计数为1。如果再次看到它,则更改该单词在哈希中存储的值。

完成后,在哈希中查找计数。

(我不再赘述,因为这看起来像是一个家庭作业问题。如果您遇到问题,请老师解释一下。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM