给出一些
local variables,在Ruby中使用
compact它们最简单的方法是什么?
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{} )
但它并不完美,因为你必须通过一个过程.我愿意接受如何改进它的建议.