initialization of local variables

For some reason I feel a need to initialize variables in some cases as
the way "rec" is done in
the code below where I do "rec = nil". I know ruby would initialize it
by default, but there are some scenarios where I am not sure that is
always the case, but I forget exactly except that it seems like it has
happened.

Can someone comment on this. I seem to carry over idioms from my C++
coding days ..

def self.get(attr)
    rec = nil
    if id = params[:id]
      rec = self.find_by_id(id)
    else
      guid = attr[:guid]
      client_id = attr[:client_id]
      rec = self.find(:first, :conditions =>
            ["guid = :guid and cdr_client_id = :client", {:guid =>
guid, :client => client_id}])
    end
    rec
end

For some reason I feel a need to initialize variables in some cases as

the way “rec” is done in

the code below where I do “rec = nil”. I know ruby would initialize it

by default, but there are some scenarios where I am not sure that is

always the case, but I forget exactly except that it seems like it has

happened.

Hi Jedrin,

You may be thinking of scoping issues. If you need to access a local variable in a block to set it’s value, and then use it outside of the block, you will need to initialize it prior to the block.

def test_method

test_block do |val|

var = ‘FAIL’

end

puts var

end

will result in an ‘undefined local variable or method’ error. If you initialise var prior to the block, then you can set the value in the block, and it will be accessible after the block as so:

def test_method

var = nil

test_block do |val|

var = ‘SUCCESS’

end

puts var

end

will result in ‘SUCCESS’ being output.

HTH

Paul

Ok, I guess that's what it is, I know I have seen something like
that, it's the code blocks that behave differently.

  It's sort of interesting that where branching is concerned it works
as bellow where local vars assignments that never get executed get set
to nil as in the value of k

def myfunc

  x = 2
  z = 1

  if x
    y = 3
    if z == 3
      k = 5
    end
  end

  p y
  p k

end

myfunc

I would be curious if someone could explain to me the philosophy of
why k works in my last example the way it does.

As far as the code blocks, I guess they can be standalone, closures,
what not. I'm a bit rusty on what you can do with that sort of thing,
though I have touched on it a bit ..

I guess it kind of makes sense anyway. I feel I can write code better
since now I understand the distinction with the code blocks as opposed
to the branching ..