从给定一个对象的对象
问题描述:
访问变量的名称:从给定一个对象的对象
object_name = "hello"
有没有什么办法让变量的名称"object_name"
?我需要创建一个带有变量名称和值的字符串,例如
"The name of the variable is 'object_name' and its value is 'hello'"
我想:
object_name.object_id
# => 20084556
答
我能想出的唯一办法是沿着这些路线的东西:
binding.local_variables.each do |var|
puts "The name of the variable is '#{var}' and its value is '#{eval(var.to_s)}'"
# or
# puts "The name of the variable is '#{var}' and its value is '#{binding.local_variable_get(var)}'"
end
# The name of the variable is 'object_name' and its value is 'hello'
当然会输出所有局部变量当前在范围,以及,eval
。
+2
你可以使用'binding.local_variable_get(“variable”)'而不是'eval' http://stackoverflow.com/a/30840502/584552 – mdesantis
答
def find_var(in_binding, object_id)
name = in_binding.local_variables.find do |name|
in_binding.local_variable_get(name).object_id == object_id
end
[name, in_binding.local_variable_get(name)]
end
the_answer = 42
find_var binding, the_answer.object_id # => [:the_answer, 42]
foo = 'bar'
baz = [foo]
find_var binding, baz.first.object_id # => [:foo, "bar"]
明显的垮台 - 指向同一个对象的两个变量。阿卡
a = b = 42
答
只是出于好奇:
object_name = "hello"
var_name = File.readlines(__FILE__)[__LINE__ - 2][/\w+(?=\s*=)/]
puts "Variable named '#{var_name}' has value '#{eval(var_name)}'"
> ruby /tmp/d.rb
#⇒ Variable named 'object_name' has value 'hello'
答
我花了一段时间,但我解决了这个最终。感谢上述所有答案。以下是我用来解决问题的功能文件,步骤定义和方法。
Feature: try and work out a simple version of the f2d pages that could be used for all
Scenario Outline: first go
Given I set up an object for these things
| page_1 | page_2 |
| <page_1> | <page_2> |
Then I create objects and output two things for one
Examples:
| page_1 | page_2 |
| elephants | scary pants |
步骤定义:
Given(/^I set up an object for these things$/) do |table|
set_up_a_hash_from_a_table(table)
end
Then(/^I create objects and output two things for one$/) do
do_something_with_a_hash
end
方法:
def set_up_a_hash_from_a_table(table)
@objects = Hash.new
@summary = Array.new
data = table.hashes
data.each do |field_data|
@objects['page_1'] = field_data['page_1']
@objects['page_2'] = field_data['page_2']
end
end
def do_something_with_a_hash
show_me_page_1
show_me_page_2
puts "Summary is #{@summary}"
end
def show_me_page_1
do_stuff_for_a_page('page_1')
end
def show_me_page_2
do_stuff_for_a_page('page_2')
end
def do_stuff_for_a_page(my_object)
puts "key is #{my_object} and value is #{@objects[my_object]}"
@summary.push("#{my_object} - #{@objects[my_object]}")
end
结果:
#=> key is page_1 and value is elephants
#=> key is page_2 and value is scary pants
#=> Summary is ["page_1 - elephants", "page_2 - scary pants"]
当然不是。 ... – sawa
...并希望永远不会;-) – Stefan
[从表示局部变量的字符串获取值]的可能重复(http://stackoverflow.com/questions/30840127/get-value-from-string-representing -local-variable) – mdesantis