2

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@user705586: Out of curiosity, are you coming from PHP? I think that arrays and hashes are the same thing there.
1

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

Comments

1

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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.