Don't understand how to use lambdas, hashes, or if


#1



I don't have a specific lesson to link to, I'm just trying to understand how to use blocks, procs, and lambdas.


What I expect my code to do: print out
{ "pivot0"=>5, "left0"=>[5,0,1,2,3,4], "right0"=>[6,7,8,9] }

What my code does: print out { "pivot0"=>5}

I've used print to try to debug. It appears that inside the lambda, the program is pushing ALL numbers into both hash["left0"] and hash["right0"], not just the appropriate ones. Yet "left0" and "right0" aren't showing up at all inside hash. I've tried a proc, too, but it's no different. What am I not understanding?


source = [5,0,1,2,3,4,6,7,8,9]

hash = Hash.new([])

l=0

hash['pivot' + l.to_s] = source[0]

branch = lambda do |e|
    
    if e <= hash['pivot' + l.to_s]
        hash['left'+l.to_s].push(e)
    else
        hash['right'+l.to_s].push(e)
    end
    
end

source.each &branch

print hash


#2

This question has now been answered here.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.