什么是PHP的紧凑型Ruby相当于什么?
发布时间:2020-12-13 14:10:15 所属栏目:PHP教程 来源:网络整理
导读:给出一些 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,
给出一些
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的 方法 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{} ) 但它并不完美,因为你必须通过一个过程.我愿意接受如何改进它的建议. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |