开发者

How to fetch a certain value from a hashtable

开发者 https://www.devze.com 2023-04-12 17:22 出处:网络
values = [] values << [ \'1\', \'one\'] values << [ \'2\', \'two\'] values << [ \'3\', \'three\']
values = []
values << [ '1', 'one']
values << [ '2', 'two']
values << [ '3', 'three']

o开发者_运维技巧ne = '1'

puts values[one]

The above line throws an exception.


You defined an array, you want a hash.

values = {}
values['1'] = 'one'
values['2'] = 'two'
values['3'] = 'three'

one = '1'
values[one] #=> 'one'

That of course you should write:

values = {
 '1' => 'one',
 '2' => 'two',
 '3' => 'three',
}

one = '1'    
values[one] #=> 'one'


That's not a Hash table; that's an array. values has the value: [['1', 'one'], ['2', 'two'], ['3', 'three']]

The code you were looking for is:

values = {'1' => 'one', '2' => 'two'}
values['3'] = 'three'

one = '1'

puts values[one] # => 'one'


Like others have pointed out, its really not a hash table its more like 2-dimensional array. Although not effective to retrieve values this way. An approach to obtain value from this structure could be

values.select { |entry| entry[0].eql? '1' }[0][1]


You can convert an array of key value pairs into a hash:

values = []
values << [ '1', 'one']
values << [ '2', 'two']
values << [ '3', 'three']

hash = Hash[values]
hash['1'] # => "one"

This uses the Hash.[] method, which is described at this ruby-doc.org page.

0

精彩评论

暂无评论...
验证码 换一张
取 消