user1946705
user1946705

Reputation: 2888

Ruby - array with indexes

how can I do in Ruby an array with indexes? My custom from PHP is something like this:

@my_array = [0 => "a", 3 => "bb", 7 => "ccc"]

And this array I want to go through each_with_index and I would like to get the result, e.g. in a shape:

0 - a
3 - bb
7 - ccc

Can anyone help me, how to do? Thanks

Upvotes: 2

Views: 1428

Answers (3)

Mat
Mat

Reputation: 206699

They're called hashes in ruby.

h = { 0 => "a", 3 => "bb", 7 => "ccc" }
h.each {|key, value| puts "#{key} = #{value}" }

Reference with a bunch of examples here: Hash.

Upvotes: 4

Ell
Ell

Reputation: 4358

Arrays in ruby already have indexes but if you want an associative array with index of your choice, use a Hash:

@my_array = {0 => "a", 3 => "bb", 7 => "ccc"}

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124642

You don't want an array, you want to use a hash. Since your indices are not sequential (as they would/should be if using an array), use a hash like so:

@my_hash = { 0 => 'a', 3 => 'bb', 7 => 'ccc' }

Now you can iterate through it like this:

@my_hash.each do |key, value|
  num = key
  string = value
  # do stuff
end

Upvotes: 1

Related Questions