Ruby: interpolated string for variable name

In Ruby, how can I interpolate a string to create a variable name?

I want to be able to set such a variable:

"post_#{id}" = true

This returns a syntax error, funny enough:

syntax error, unexpected '=', expecting keyword_end
+4
source share
2 answers

I believe you can do something like:

  send("post_#{id}=", true)

This will require, of course, that you have the appropriate setter / receiver. That since you are doing this dynamically, you probably are not doing it.

So, perhaps you could do:

  instance_variable_set("@post_#{id}",true)

To get a variable:

  instance_variable_get("@post_#{id}")

By the way, if youโ€™re tired of typing instance_variable_set("@post_#{id}",true), just for fun you can do something like:

class Foo

  def dynamic_accessor(name) 
    class_eval do 
      define_method "#{name}" do
        instance_variable_get("@#{name}")
      end
      define_method "#{name}=" do |val|
        instance_variable_set("@#{name}",val)
      end
    end
  end

end

In this case, you could:

2.3.1 :017 > id = 2
 => 2 
2.3.1 :018 > f = Foo.new
 => #<Foo:0x00000005436f20> 
2.3.1 :019 > f.dynamic_accessor("post_#{id}")
 => :post_2= 
2.3.1 :020 > f.send("post_#{id}=", true)
 => true 
2.3.1 :021 > f.send("post_#{id}")
 => true 
2.3.1 :022 > f.send("post_#{id}=", "bar")
 => "bar" 
2.3.1 :023 > f.send("post_#{id}")
 => "bar" 
+4

. ,

id = 1
s = "post_#{id}"
  #=> "post_1"

Ruby v1.8 . , post_1 , - :

post_1 = false

post_1 ,

b = binding
b.local_variable_get(s)
  #=> false

( b.local_variable_get(s.to_sym))

b.local_variable_set(s, true)
  #=> true
post_1
  #=> true

( b.local_variable_set(s.to_sym, true)).

. Binding # local_variable_get # local_variable_set.

0

Source: https://habr.com/ru/post/1677703/


All Articles