开发者

Ruby - array with indexes

开发者 https://www.devze.com 2023-03-15 17:45 出处:网络
how can I do in Ruby an arr开发者_StackOverflow中文版ay with indexes? My custom from PHP is something like this:

how can I do in Ruby an arr开发者_StackOverflow中文版ay 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


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.


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


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

精彩评论

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

关注公众号