A fairly simple question, but I don't see it anywhere on SO, and I'm a Ruby noob.
In Ruby, if I have a hash, similar to this.
hashOne = {'dog' => 'canine', 'cat' => 'feline', 'me' => 'rubynooby'}
And let's assume that I want to replace the value a couple of different ways.
Method 1
Let's say I want to replace the value of me
with rubypro
. I've seen this done this way:
hashOne[:me] = "rubypro"
but I haven't seen a solution to replacing the value by which number it is, for example, let's assume that I always want to change the 3rd key (and assuming it starts on 1 and not 0)
Method 2 - These don't work
hashOne[3] = "rubypro"
or
hashOne.values[3] = "rubypro"
I haven't seen any examples of this, or a question about it on SO. Can someone point me in that direction?
The reason I was trying to work on this, is because I have a Hash, where I don't know what the key is, but I know what I want the value to be. It's weird, but that's where I'm at.
答案 0 :(得分:1)
You can try this:
hashOne[hashOne.keys.unshift('')[3]] = "rubypro"
答案 1 :(得分:0)
You can do hashOne[hashOne.keys[3]] = 'rubypro'
. Also I remember reading that Hashes in ruby are ordered but I'm not entirely sure. (Be careful with using indices because they may not be ordered in other languages) I would ensure that the keys are always returned in the same order before trying to assign a key with an index.
If you really wanted to use an index, I'd recommend using an array because that's not the purpose of a key/value hash.