给出一个对象:
object_name = "hello"
有没有办法获取变量的名称"object_name"
?我需要创建一个包含变量名称及其中的值的字符串,例如
"The name of the variable is 'object_name' and its value is 'hello'"
我试过了:
object_name.object_id
# => 20084556
答案 0 :(得分:3)
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
答案 1 :(得分:1)
我能想出的唯一方法是:
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 :(得分:1)
出于好奇:
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'
答案 3 :(得分:0)
我花了一段时间,但最终解决了这个问题。感谢所有上述答案。以下是我用来解决的功能文件,步骤定义和方法。
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"]