php - 如何在 Ruby 中复制此 PHP 代码?

标签 php ruby lambda closures

我正在将一些项目转移到 Rails,我想复制这段 PHP 代码:

http://www.php.net/manual/en/functions.anonymous.php#106046

到目前为止我有这个:

def html (tag, id = "", hclass = "")
  hopen = "<#{tag}"
  hclose = "</#{tag}>"
  unless id == ""
    hopen += " id=\"#{id}\""
  end

  unless hclass == ""
    hopen += " class=\"#{hclass}\""
  end

  hopen += ">"

  return lambda  { |data| print hopen,data,hclose}
end

我需要创建可变变量,如下所示: PHP

$layout = array('container','header','pmain','lsidebar','rsidebar','footer');

foreach ($layout as $element)
   $$element = html ("div", $element);

这是我的 RUBY 原型(prototype)

layout = [:body, :header, :sidebar, :footer]

##I know this isn't right, but how do I create the dynamic functions like PHP???
layout.each {|x| instance_variable_set "@#{x}", 0 }

此外,我需要调用函数,没有调用方法是否仍然可以调用函数?如果我必须嵌套调用,它会很困惑。

h1 = html(:h1)
mainx =  html(:div )
puts mainx.class
puts mainx.call(h1.call("Blog!")) 

最佳答案

您在这里做了很多工作,但这里有一些过渡方面的帮助:

$layout = array('container','header','pmain','lsidebar','rsidebar','footer');

foreach ($layout as $element)
  $$element = html ("div", $element);

据我所知,这是一个数组转换,所以等价于:

layout = [ @container, @header, @pmain, @lsidebar, @rsidebar, @footer]

layout.collect! do |element|
  # Using the built-in content_tag method instead of
  # the custom reimplementation with curried parameters.
  content_tag("div", element)
end

Ruby 没有取消引用变量的方法,因为 Ruby 中变量的行为方式完全不同。实例变量在对象的上下文中持久存在,而变量仅在给定范围内持久存在。您可以通过名称获取和设置任意实例变量,但通常不能对局部变量执行相同操作。除了 eval { var } 之外,在 Ruby 中没有等价的 $$var ,由于它如何评估潜在的任意代码,这真的很不受欢迎。

不过,对于您为什么需要这样做,我真的有一种不好的预感。模板应该是一种解决必须在这种低级别上争论的方法。

如果您是 Ruby 新手,最好通读有关 String 和 Array 的文档,因为它们都充满了有用的方法。 Array 还包括 Enumerable 模块,它增加了更多内容。

关于php - 如何在 Ruby 中复制此 PHP 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7772657/

相关文章:

php - Laravel 搜索查询 - 'OR' 和 'AND' 的 SQL 排序破坏了 foreach 循环查询

php - 如何使用 Laravel 5.5 禁用 Chrome 的 Dusk headless 模式?

php - 登录时重定向到不同页面 - php

ruby - 将数组作为命令参数传递

c++ - 将 lambda 函数作为回调传递和存储

java - 在 Java 中将函数应用于 while 循环

php - 使用 AJAX 数据更新数据库

作为散列值的 Ruby 函数

ruby-on-rails - Ruby/Rails 初学者可以将 Ruby 1.9 与 Rails 一起使用吗?

c++ - 如何在 std::transform 的 vector 中使用其他值?