Friday, September 17, 2010

Ruby magic variables

Playing in irb console a little bit and I found interesting behaviour:
irb(main):001:0> defined? x
=> nil
irb(main):002:0> x
NameError: undefined local variable or method `x' for main:Object
        from (irb):2
irb(main):003:0> x = 1 if false
=> nil
irb(main):004:0> defined? x
=> "local-variable"
irb(main):005:0> x
=> nil
Looks like ruby allocates memory for all variables, even when the block was not executed.

With this knownledge we can simlify our if / while statements.
So, as an example, we can change this:
irb(main):012:0> if false == true
irb(main):013:1> z = "not possible"
irb(main):014:1> else
irb(main):015:1* z = nil
irb(main):016:1> end
=> nil
irb(main):017:0> print "Output: #{z}"
into this:
irb(main):019:0> if false == true
irb(main):020:1> z = "not possible"
irb(main):021:1> end
=> nil
irb(main):022:0> print "Output: #{z}"
Output: => nil
As you see z variable was allocated (and set to default nil) and we don't need to initialize it "one more time".

Happy refactoring :)

No comments:

Post a Comment