【问题标题】:String Replace Regex like mustache js for RubyString Replace Regex like mustache js for Ruby
【发布时间】:2014-10-29 02:21:59
【问题描述】:

我是 ruby​​ 的新手,正在尝试制作一个简单的函数,该函数将获取一个文件并用数组替换所有的胡须。例如:

simple.tpl

<p>Hello {{person_name}}</p>
<p>{{welcome_msg}}</p>

我想用一组键和值来改变它。

class Template

    attr_accessor :file_name

    def parse_template (array_to_replace)
        str = File.read(file_name)

        array_to_replace.each do |item|
        # required code here ...
        end

        return str
    end

end

任何人都可以输入所需的代码???

预期输出

我不知道多维数组在 ruby​​ 中是如何工作的,但我想要的是:

the_arr = Array(
   :person_name => "John Doe",
   :welcome_msg => "Hello friend"
)
object = Template.new
object.file_name = "simple.tpl"
output = object.parse_template(the_arr);

puts output

我应该得到

<p>Hello John Doe</p>
<p>Hello friend</p>

【问题讨论】:

  • 显示您的预期输出..
  • 你应该先完成基本的 Ruby 教程。
  • 嗯,为什么?我的代码中有这么多错误吗?
  • 我这么说是因为你使用了Array() 语法。这是非常罕见的,表明您还没有真正尝试过学习 Ruby,您只是将 PHP 语法转换为 Ruby 语法。但是,学习 Ruby 不仅需要学习语法,还可能需要了解一些新概念。您可能想要的是Hash,任何基本的 ruby​​ 教程都将在第一部分介绍。

标签: html ruby regex webrick


【解决方案1】:

你可以使用the mustache gem:

require 'mustache'

attributes = {
  :person_name => "John Doe",
  :welcome_msg => "Hello friend"
}

template = File.read('simple.tpl')

output = Mustache.render(template, attributes)

puts output
# <p>Hello John Doe</p>
# <p>Hello friend</p>

【讨论】:

  • attributes = { :person_name =&gt; "John Doe", :welcome_msg =&gt; "Hello friend" } 这是一个数组还是对象??
  • @Anonymous 它是一个哈希,也是一个对象
  • 你遇到了 Ruby 的另一个属性:everything 是一个对象。
  • 我们如何检索say :person_name 的值?喜欢attributes.person_name ??
  • 我不想重复自己,但你真的应该阅读教程!
【解决方案2】:

您可能对 Ruby 的内置功能感兴趣。

string = '<p>Hello %{person_name}</p>
          <p>%{welcome_msg}</p>'

attributes = {
  :person_name => "John Doe",
  :welcome_msg => "Hello friend"
}

puts string % attributes

输出:

<p>Hello John Doe</p>
<p>Hello friend</p>

解释:

String class 定义了一个名为 % 的方法(是的,在 Ruby 中,方法名称中可以包含非字母数字字符)。这会将%{key} 替换为来自哈希值的模板样式。它还可以对数字和字符串进行格式化;请参阅documentation of the % method 了解更多信息。

【讨论】:

  • % 的符号是什么??
  • 我添加了一个解释。
  • 非常感谢您,我会支持您的回答。非常感谢
  • 是的,我知道......但之前的答案更好。无论如何,你有 19.k repu .. 你还想要什么 ;) 还是谢谢
  • @Anonymous SO 不是要尽可能多地积累代表,而是要找到最好的答案。您应该接受能够最好地回答您的问题和/或以最佳方式解决您的问题的答案 - 有时这是一个不直接回答问题的帖子,而是试图提出解决相同问题的替代方法问题更优雅。
猜你喜欢
  • 1970-01-01
  • 2019-02-19
  • 2023-03-20
  • 2016-06-25
  • 2014-01-17
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多