today I've got a very difficult task from my senior(perhaps it difficult only for me).
The task is like this:
He give me several string data(to be precise 8 string data). I can choose to store it in array or a hash.
"hello", "you", "great", "you", "great", "hello", "great", "great"Now I must combine the same data from those strings. I mean if I put them inside an array.
myary = ["hello", "you", "great", "you", "great", "hello", "great", "great"]I must make it become like this
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.I can use hash if I want, but the problem is, I can't find a good way to do this. I have struggle for several hours and it's futile. The best I can done is here:
I store them in a hash.
myhash = {
1 => "hello",
2 => "you",
3 => "great",
4 => "you",
5 => "great",
6 => "hello",
7 => "great",
8 => "great",
}
Then I write this code:
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
This will give the output:
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!!
As you can see I'm screwed, I know the code is wrong, but believe me I nearly bang my head onto the wall because this matter. Someone please, I need serious help. Oh I want to make sure something, does the task is possible to accomplish or not? I just want to make sure that my senior is not teasing me with the task. But in fact I want to know if this really possible. Sorry if I've done something wrong. Thank you very much. Please no flaming :) After all I just asking, if you feel didn't like to give answer or else, then simply leave. Positive answer very appreciated.