给定一些 local variables , 最简单的方法是什么 compact
他们在 Ruby 中?
def foo
name = 'David'
age = 25
role = :director
...
# How would you build this:
# { :name => 'David', :age => 25, :role => :director }
# or
# { 'name' => 'David', 'age' => 25, 'role' => :director }
end
在 PHP 中,我可以简单地这样做:
$foo = compact('name', 'age', 'role');
最佳答案
我对原来的答案有了重大改进。如果您从 Binding
本身继承它会更干净。 to_sym
之所以存在,是因为旧版本的 ruby 将 local_variables
作为字符串。
实例方法
class Binding
def compact( *args )
compacted = {}
locals = eval( "local_variables" ).map( &:to_sym )
args.each do |arg|
if locals.include? arg.to_sym
compacted[arg.to_sym] = eval( arg.to_s )
end
end
return compacted
end
end
用法
foo = "bar"
bar = "foo"
binding.compact( "foo" ) # => {:foo=>"bar"}
binding.compact( :bar ) # => {:bar=>"foo"}
原始答案
这是我能找到的最接近 Php 的 compact
的方法。 -
方法
def compact( *args, &prok )
compacted = {}
args.each do |arg|
if prok.binding.send( :eval, "local_variables" ).include? arg
compacted[arg.to_sym] = prok.binding.send( :eval, arg )
end
end
return compacted
end
示例用法
foo = "bar"
compact( "foo" ){}
# or
compact( "foo", &proc{} )
虽然它并不完美,因为你必须传递一个过程。我愿意接受有关如何改进它的建议。
关于php - 什么是 Ruby 等同于 PHP 的紧凑型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17423127/