什么是PHP的紧凑型Ruby相当于什么?

前端之家收集整理的这篇文章主要介绍了什么是PHP的紧凑型Ruby相当于什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给出一些 local variables,在Ruby中使用 compact它们最简单的方法是什么?
  1. def foo
  2. name = 'David'
  3. age = 25
  4. role = :director
  5. ...
  6. # How would you build this:
  7. # { :name => 'David',:age => 25,:role => :director }
  8. # or
  9. # { 'name' => 'David','age' => 25,'role' => :director }
  10. end

PHP中,我可以简单地这样做:

  1. $foo = compact('name','age','role');
我的原始答案得到了显着改善.如果从Binding本身继承,它会更清晰. to_sym就在那里,因为旧版本的ruby将local_variables作为字符串.

实例方法

  1. class Binding
  2. def compact( *args )
  3. compacted = {}
  4. locals = eval( "local_variables" ).map( &:to_sym )
  5. args.each do |arg|
  6. if locals.include? arg.to_sym
  7. compacted[arg.to_sym] = eval( arg.to_s )
  8. end
  9. end
  10. return compacted
  11. end
  12. end

用法

  1. foo = "bar"
  2. bar = "foo"
  3. binding.compact( "foo" ) # => {:foo=>"bar"}
  4. binding.compact( :bar ) # => {:bar=>"foo"}

原始答案

这是我能找到的行为类似PHPcompact的最接近的方法

方法

  1. def compact( *args,&prok )
  2. compacted = {}
  3. args.each do |arg|
  4. if prok.binding.send( :eval,"local_variables" ).include? arg
  5. compacted[arg.to_sym] = prok.binding.send( :eval,arg )
  6. end
  7. end
  8. return compacted
  9. end

示例用法

  1. foo = "bar"
  2. compact( "foo" ){}
  3. # or
  4. compact( "foo",&proc{} )

但它并不完美,因为你必须通过一个过程.我愿意接受如何改进它的建议.

猜你在找的PHP相关文章