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!
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!
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
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:
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}