Skip to content

Instantly share code, notes, and snippets.

@deepak
Created May 15, 2014 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepak/84d70b1ac6bcc64dd820 to your computer and use it in GitHub Desktop.
Save deepak/84d70b1ac6bcc64dd820 to your computer and use it in GitHub Desktop.
local variable shadows ivar
class Foo
attr_accessor :params
def initialize(params)
@params = params
end
def process(params)
puts "====> before: #{params.inspect}"
params.merge!(local: "modifications")
puts "====> after: #{params.inspect}"
end
end
params = { initial: "hash" }
foo = Foo.new(params)
puts "====> initial global: #{params.inspect}"
puts "====> initial in foo: #{foo.params.inspect}"
foo.process(something: "new")
puts "====> foo: #{foo.params.inspect}"
__END__
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
====> initial global: {:initial=>"hash"}
====> initial in foo: {:initial=>"hash"}
====> before: {:something=>"new"}
====> after: {:something=>"new", :local=>"modifications"}
====> foo: {:initial=>"hash"}
@iffyuva
Copy link

iffyuva commented May 15, 2014

usecase is not about shadowing, but about modifying what is passed.

class Foo
  attr_accessor :params

  def initialize(params)
    params.merge!(hello: 'world')
  end
end

params = { initial: "hash" }
puts "====> initial global: #{params.inspect}"
foo = Foo.new(params)
puts "====> initial in foo: #{foo.params.inspect}"
puts "====> global: #{params.inspect}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment