How to dynamically create a local variable?

后端 未结 4 2207
温柔的废话
温柔的废话 2020-11-22 03:46

I have a variable var = \"some_name\" and I would like to create a new object and assign it to some_name. How can I do it? E.g.

var         


        
4条回答
  •  我在风中等你
    2020-11-22 04:25

    You cannot dynamically create local variables in Ruby 1.9+ (you could in Ruby 1.8 via eval):

    eval 'foo = "bar"'
    foo  # NameError: undefined local variable or method `foo' for main:Object
    

    They can be used within the eval-ed code itself, though:

    eval 'foo = "bar"; foo + "baz"'
    #=> "barbaz"
    

    Ruby 2.1 added local_variable_set, but that cannot create new local variables either:

    binding.local_variable_set :foo, 'bar'
    foo # NameError: undefined local variable or method `foo' for main:Object
    

    This behavior cannot be changed without modifying Ruby itself. The alternative is to instead consider storing your data within another data structure, e.g. a Hash, instead of many local variables:

    hash = {}
    hash[:my_var] = :foo
    

    Note that both eval and local_variable_set do allow reassigning an existing local variable:

    foo = nil
    eval 'foo = "bar"'
    foo  #=> "bar"
    binding.local_variable_set :foo, 'baz'
    foo  #=> "baz"
    

提交回复
热议问题