Associative Arrays in Ruby

Associative Arrays in Ruby

Unlike PHP which conflates arrays and hashes, in Ruby (and practically every other language) they're a separate thing.

http://ruby-doc.org/core/classes/Hash.html

In your case it'd be:

a = {'Peter' => 32, 'Quagmire' => 'asdas'}

There are several freely available introductory books on ruby and online simulators etc.

http://www.ruby-doc.org/

Ruby: dynamically fill associative array

In Ruby a Hash can be treated as an associative array.

# Initialize the hash.
noises = {}
# => {}

# Add items to the hash.
noises[:cow] = 'moo'
# => { :cow => 'moo' }

# Dynamically add items.
animal = 'duck'
noise = 'quack'
noises[animal] = noise
# => { :cow => 'moo', 'duck' => 'quack' }

As you can see anything can be a key, in this example I have used both a symbol, :cow and a String, 'duck'.

The Ruby Hash documentation contains all the examples you could ever need.

Associated array in Ruby

I think you're confusing arrays with hashes. In this particular example

x = [1,"Jef",:three,4]

incidently x[1] is equal to "Jef", but thats because element at 1st index of x is "jeff" (which should be obvious as x is an Array), not because every two elements are key value pairs as in a a Hash.

The error

no implicit conversion of Symbol into Integer (TypeError)

is probably because you tried something like x[:three], which is obviously invalid.

This could work if your x looks something like this.

x = { 1 => "Jef", :three => 4 }

Then x[:three] will result in desired result 4.

Remember Arrays and Hashes in Ruby are two different concepts.

:three is a Symbol which are essentially strings with few twists.

Suggestion : If you want to learn basic Ruby stuff you can read up on Rubymonk. I has great content.

Associative arrays (or hash) php to ruby

A more-or-less direct rewrite from your PHP:

albums = {}
songs = [
{ :title => 'Title 1', :artist => 'Artist 1', :album => 'Album 1' },
{ :title => 'Title 2', :artist => 'Artist 2', :album => 'Album 2' },
{ :title => 'Title 3', :artist => 'Artist 1', :album => 'Album 1' },
{ :title => 'Title 4', :artist => 'Artist 2', :album => 'Album 1' },
{ :title => 'Title 5', :artist => 'Artist 3', :album => 'Album 1' }
]
songs.each do |song|
album = albums[song[:album]] ||= {}
album[:title] = song[:title]
(album[:songs] ||= []).push(song)
end
puts albums.inspect

Easier would be the one-liner:

albums = songs.group_by { |song| song[:album] }

Arrays have only integer keys, and allocate all of them up to the highest one (so if you assign foo[100] = 1, there will be locations for keys 0-99 also occupying memory (with nil value); you note array values with square brackets: [1, 2, 3] is a 3-element array, [] is empty.

Hashes are enclosed in curly braces {}, and can have pretty much anything as keys. However, blocks can also be written with braces, so take care not to confuse the two.

How to use an associative array?


i = 2
a = { 1=>'',2=>'some',3=>'..' }
p a[i]

Why are Ruby hashes called hashes, and not maps, dicts, tables or associatve arrays?

Ruby takes a large amount of inspiration from Perl, and Perl calls this a hash.

UPDATE:

Confirmed by Yukihiro Matsumoto, creator of Ruby: https://twitter.com/yukihiro_matz/status/547516495249428480

Ruby associative array calculation

It is not very beautiful but it works.

x =   [[1,2],[1,3],[0,1],[0,2],[0,3],[1,5],[0,4],[1,6],[0,9],[1,9]]

p Hash[
x.group_by(&:first)
.map do |key, val|
[key,val.map(&:last).inject(:+)]
end
] # => {1=>25, 0=>19}

On second thought, this is simpler:

result = Hash.new(0)
x.each{|item| result[item.first] += item.last}
p result # => {1=>25, 0=>19}

Read a file into an associative array

Can be done in 3 lines (This is why I love Ruby)

scores = File.readlines('/scripts/test.txt').map{|l| l.split(/\s+/)}
headers = scores.shift
scores.map!{|score|Hash[headers.zip(score)]}

now scores contains your hash array

Here is a verbose explanation

#open the file and read 
#then split on new line
#then create an array of each line by splitting on space and stripping additional whitespace
scores = File.open('scores.txt', &:read).split("\n").map{|l| l.split(" ").map(&:strip)}
#shift the array to capture the header row
headers = scores.shift
#initialize an Array to hold the score hashs
scores_hash_array = []
#loop through each line
scores.each do |score|
#map the header value based on index with the line value
scores_hash_array << Hash[score.map.with_index{|l,i| [headers[i],l]}]
end
#=>[{"KeyName"=>"Key1", "Val1Name"=>"Val1-1", "Val2Name"=>"Val2-1", "..."=>"...", "ValMName"=>"ValM-1"},
{"KeyName"=>"Key2", "Val1Name"=>"Val1-2", "Val2Name"=>"Val2-2", "..."=>"...", "ValMName"=>"ValM-2"},
{"KeyName"=>"Key3", "Val1Name"=>"Val1-3", "Val2Name"=>"Val2-3", "..."=>"...", "ValMName"=>"ValM-3"},
{"KeyName"=>"..", "Val1Name"=>"..", "Val2Name"=>"..", "..."=>"..", "ValMName"=>".."},
{"KeyName"=>"KeyN", "Val1Name"=>"Val1-N", "Val2Name"=>"Val2-N", "..."=>"...", "ValMName"=>"ValM-N"}]

scores_hash_array now has a hash for each row in the sheet.

Ruby: Looping and calling associative arrays (TypeError no implicit conversion of String into Integer)

you can loop through node['nginx'] like this. (i don't know what node.default['nginx'] is supposed to be)

node['nginx'].each do |num, hash|
#on the first iteration:
# num = 0
# hash = {'server_name' => 'black.domain.com', 'app_server' => 'http://10.50.0.163:8090', 'redirect_path' => '/mesh'}
#on the second iteration
# num = 1
# hash = {'server_name' => 'red.domain.com', 'app_server' => 'http://10.50.0.163:8090', 'redirect_path' => '/mesh'}
#now you can do what you want with the data eg
Chef::Log.info hash['app_server']
end


Related Topics



Leave a reply



Submit