php - 什么是 Ruby 等同于 PHP 的紧凑型?

标签 php ruby

给定一些 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/

相关文章:

ruby-on-rails - 关于运行 rake db :seed task 的问题

php - 使用mysqli函数向mysql插入数据

mysql - 如何将整数转换为日期时间?

ruby-on-rails - 无法获取要设置或保存的非质量分配值

php - 如何跟踪收件人打开了哪些(或多少)电子邮件?

ruby-on-rails - Rails 获取 url

ruby-on-rails - ruby rails 3 : How to access an attribute of each record in a has_many query

php - Laravel 5 Namespace 问题 fatal error 异常

php - 如何在考虑事务的情况下使用prepare语句向MySQLi中的三个不同表插入数据

javascript - iframe 和 JavaScript 位于不同页面