今天我从我的老人有一个非常困难的任务(也许只是对我来说很难)。红宝石相同的元素数组或值在散列,团结它,
的任务是这样的:
他给我几个字符串数据(准确地说8个字符串数据)。我可以选择将其存储在数组或散列中。
"hello", "you", "great", "you", "great", "hello", "great", "great"
现在我必须结合这些字符串中的相同数据。我的意思是如果我把它们放入数组中。
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!!
正如你可以看到我搞砸了,我知道的代码是错误的,但相信我,因为这件事,我差点把我的头撞到墙上。有人请,我需要认真的帮助。 哦,我想确定一些事情,这项任务是否有可能完成?我只是想确保我的大四不是在挑剔我的任务。但事实上,我想知道这是否真的有可能。 对不起,如果我做错了什么。非常感谢你。请不要燃烧:)毕竟我只是问,如果你觉得不喜欢回答或其他问题,那就干脆离开。肯定的答复非常感谢。
Woaah,这真是太好了,我从来没有知道GROUP_BY方法。非常感谢。 :) – LuminaChen