-1

I wanna change the index of a given array:

arr = ["cat", "tiger", "lion"]

so lion-item will have the value of 5-index, tiger will have value of 4-index and 3 for cat-item

is this possible?

Thanks!

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
YoniGeek
  • 4,053
  • 7
  • 27
  • 30

3 Answers3

1

You cannot do it with each_with_index, but you can do it with with_index.

arr.each.with_index(3) do |e, i|
  ...
end
sawa
  • 165,429
  • 45
  • 277
  • 381
1

Yes it's possible you can create a index method to acces it.

def get_by_index(array, value)
  array[value-3]
end

You can also create a new array child class who inherits from array and redefine an square bracket method as explained here:

How does defining [square bracket] method in Ruby work?

Community
  • 1
  • 1
Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35
0

You could do that with a Hash:

hash = {
  3 => "cat",
  4 => "tiger",
  5 => "lion"
}

hash[4]
#=> "tiger"

If you want to convert from an Array to a Hash you can do this:

arr = ["cat", "tiger", "lion"]
hash = Hash[arr.each_with_index.map{|v,i| [i+3, v] }]
#=> {"cat"=>3, "tiger"=>4, "lion"=>5}
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168