MrNagoo MrNagoo - 5 months ago 13
Ruby Question

How does a block variable change with a nested array?

I am following a tutorial.

arr = [["cow", "moo"], ["duck", "quack"]]
bucket = arr[0]
bucket.each_with_index do |kv, i|
k, v = kv
puts k
puts v
end


I understand that when it goes through
arr[0]
, it is first
kv = cow
and
i = 0
, and then
kv = moo
and
i = 1
. How does
k, v = kv
make sense? To me, it seems that
k = kv
and
v = kv
, but that isn't the case. I don't understand the purpose.

Answer

Basically the line k, v = kv means that you are assigning kv to k or k= kv

comma separated assignment is just another way of assigning multiple variables in one line, it's just syntactic sugar.

Try messing around with your code and do something like this for example:

    arr = [["cow", "moo"], ["duck", "quack"]]
    bucket = arr[0]
    bucket.each_with_index do |kv, i|
      k, v = kv, i
      puts "k is #{k} and v is #{v}"
    end
   # k is cow and v is 0
   # k is moo and v is 1
Comments