From: Robert Klemme Date: 2010-06-27T04:45:08+09:00 Subject: Re: General Confusion On 06/25/2010 09:55 PM, Chuck Brotman wrote: > Robert, > > In looking over the code samples you provided: > ------------ > def add_edge(from, to) > (@nodes[from] ||= []) << to > self > end > > def edges(node_id) > @nodes[node_id] || [] > end > > def node(node_id) > Node.new(self, node_id) > end > end > ------------ > I find I am a puzzled: > Even given that to, from are fixnums: > 1) what does "@nodes[node_id] || []" return? It returns @nodes[node_id] if that is not nil and not false - otherwise you get a new empty Array (from [] which is just special syntax for Array.new). This is done so the caller can rely on an Array being returned from this method under all circumstances so you can do gr.edges(17).each do |node| puts "17 -> #{node}" end and do not have to verify that the result of #edges is non nil. > 2) same question for: "@nodes[from] ||= []) << to" > I could find no reference to this " ||= " syntax (in Pickax, or > other ruby texts, nor online Nor do I understand it's semantics... I don't have my Pickaxe here right now but I would be surprised to find ||= not explained. There also were some threads about operator ||= recently. It boils down to a ||= b being short for a || (a = b) In this case @nodes[from] || (@nodes[from] = []) In prose: set @nodes[from] to an empty Array if unset. The "<< to" at the end simply concatenates to the Array returned from the expression in brackets. > 3) how about Node.new(self, node_id) I have trouble with the use of > "self" here, the whole usage of "self" has caused me confusion, ever > since I started playing with OO (back when java was IT!) In a Ruby program at any point in time "self" points to an object. You cannot assign to "self". "self" is implicitly set when a method call with an explicit receiver is executed. If you execute "a.foo" then "self" is set to "a" while inside the method. Maybe you have a look at Chris Pine's learning to program. A general advice: if you are unsure about expressions you find in programs or postings here you can pretty easily try them out in IRB and see what they do. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/