iii - 1 year ago 31

Ruby Question

`def breadth_first_search(adj_matrix, source_index, end_index)`

node_queue = [source_index]

puts "#{source_index} stored into queue \n"

loop do

curr_node = node_queue.pop

puts "#{curr_node} popped \n"

return false if curr_node == nil

return true if curr_node == end_index

children = (0..adj_matrix.length-1).to_a.select do |i|

adj_matrix[curr_node][i] == 1

end

puts "children: #{children}"

node_queue = children + node_queue

puts "node_queue: #{node_queue}"

end

end

I can understand what it does conceptually, but the actual syntax is what I don't understand. Is the children variable an array that stores elements with a loop?

Answer

The variable `children`

is being set to the result of the enumerable method select

`select`

is a method often called on an array which takes a block. The return value is only the values of the original array in which the block returns a `truthy`

object (e.g. not `false`

, not `nil`

)

`(0..adj_matrix.length-1)`

is a range object, from 0 to the length of `adj_matrix`

, which is converted to an array via `to_a`

(resulting in `[0, 1, 2, ...]`

)

Then that array is filtered by `select`

to only be the values in which `adj_matrix[curr_node][i] == 1`

. So if the nodes at index `0`

and `2`

, are equal to `1`

then the result would be `[0, 2]`