回答編集履歴
2
追記
answer
CHANGED
@@ -22,4 +22,18 @@
|
|
22
22
|
binding.local_variable_set(:three, 3)
|
23
23
|
|
24
24
|
p [one,two,three] #=> [1, 2, 3]
|
25
|
-
```
|
25
|
+
```
|
26
|
+
|
27
|
+
|
28
|
+
---
|
29
|
+
**追記**
|
30
|
+
|
31
|
+
インスタンス変数ならば
|
32
|
+
|
33
|
+
```ruby
|
34
|
+
%w[one two three].each.with_index(1){|key, val|
|
35
|
+
instance_variable_set("@#{key}", val)
|
36
|
+
}
|
37
|
+
```
|
38
|
+
|
39
|
+
でやれます。
|
1
追記
answer
CHANGED
@@ -2,6 +2,13 @@
|
|
2
2
|
|
3
3
|
動的に変数を作りたいときは代替として[Hash](https://docs.ruby-lang.org/ja/latest/class/Hash.html)を用いるとおおよその場合、うまくいきます。
|
4
4
|
|
5
|
+
```ruby
|
6
|
+
values = ['one', 'two', 'three'].each.with_index(1).map{|key, val| [key, val] }.to_h
|
7
|
+
|
8
|
+
p values # => {"one"=>1, "two"=>2, "three"=>3}
|
9
|
+
p values["one"] # => 1
|
10
|
+
```
|
11
|
+
|
5
12
|
新しいローカル変数ではなく、事前に変数名が決まっているローカル変数の場合は
|
6
13
|
binding.local_variable_setが使えます。
|
7
14
|
|