Ruby - How to access elements in a multi-dimensional array -
i thought simple, when came downwards case wasn't able it. sense if can understand have much improve understanding of ruby.
what: want search within 2-d array of strings , integers, , homecoming index/indices of string found. these indices of each subarray placed in array in order of corresponding subarrays.
example when searching string "a":
input array: [[1,"a","a",3],[1,"b"],["a",2]]
output array: [[1,2],[],[0]]
what tried: intuitively thought like:
source = [[1,"a","a",3],[1,"b"],["a",2]]
with
source.each.each_index.select { |v| v == "a" }
or
source.each {|x| x.each_index.select { |i| x[i] == "a" }}
questions:
1) should phone call output array input array?
2) see many other enumerators , methods mashed way, how come can't in case? don't want clutter question of simpler test cases tried, either got undefined method errors or homecoming source array.
3) have blocks associated methods? modeled code after reply question: ruby: how find indices of elements match given condition? confused why seems block straight associated multiple methods. in other words, |i| #each_index while boolean #select. seems random , disorganized me right how construction these blocks (i.e why not vice versa?).
source.map { |row| row.each_index.select { |i| row[i] == "a" } } # => [[1, 2], [], [0]]
you can't because logic mistaken :) source.each {...}
homecoming source
, doesn't matter within block. homecoming result, utilize map
. source.each.each_index
calls each_index
on enumerator returned each
without block, , that's not method available on enumerators (you want each_index
on arrays).
indeed. each
block , each
without block different things.
specifically, in code above:
start source
array. map
block process block each element (called row
), , homecoming array of results. each row, row.each_index
without block homecoming iterator of indices of row
array, select
block on iterator homecoming array contain of elements.
ruby arrays multidimensional-array
No comments:
Post a Comment