Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用.gsubs在ruby中用哈希替换字符串?_Ruby - Fatal编程技术网

如何使用.gsubs在ruby中用哈希替换字符串?

如何使用.gsubs在ruby中用哈希替换字符串?,ruby,Ruby,我刚开始学习Ruby,我需要创建一个模板,用我编写的哈希替换我的字符串。我需要在代码中添加什么 这是我的代码,我为我的任务写了两个方法,请帮忙提建议 class Template def initialize(template_string, local_variables) @template_string = template_string @local_variables = local_variables end def compile() @

我刚开始学习Ruby,我需要创建一个模板,用我编写的哈希替换我的字符串。我需要在代码中添加什么

这是我的代码,我为我的任务写了两个方法,请帮忙提建议

class Template 

  def initialize(template_string, local_variables)
    @template_string = template_string
    @local_variables = local_variables
  end 

  def compile()
    @template_string.gsub()
  end
end



puts Template.new("I like %{x}", x:"coffee").compile # x = coffee
puts Template.new("x = %{x}", y:5).compile # unknown x
puts Template.new("x = %{x}", x:5, y:3).compile # x = 5, ignores y

首先,请阅读如何使用该方法。然后重写Templatecompile,如下所示:

def编译 编译=@template_string.dup @局部变量。每个do | k,v| 已编译的.gsub!%{{k}},Stringv 终止 汇编 终止 没有必要使用gsub。只需使用格式规范

def compile
  @template_string % @local_variables
end
整个例子:

class Template
  def initialize(template_string, local_variables)
    @template_string = template_string
    @local_variables = local_variables
  end 

  def compile
    @template_string % @local_variables
  end
end

Template.new("I like %{x}", x: "coffee").compile
#=> "I like coffee"

Template.new("x = %{x}", y: 5).compile
#=> KeyError (key{x} not found)

Template.new("x = %{x}", x: 5, y: 3).compile
#=> "x = 5"

你期望的结果是什么?你的问题我不清楚。据我所知,我想在回答时说我喜欢咖啡,x=5非常感谢,我试过了,在回答中我看到了最近的回溯:2:来自任务。rb:12:在`'1:来自任务。rb:12:在'new'任务中。rb:3:在'initialize'中:给出的参数数量错误2,应为0 ArgumentError请仔细检查初始化方法是否需要2个参数,如下所示:def initializetemplate_string,local_variables!请考虑一个答案,当它是有益的,并接受它时,它解决了你的问题。这是向回答者表示感谢并向其他人表明问题已解决的一种方式。非常感谢,我尝试了它,在响应中我看到了最近的回溯:2:来自任务。rb:12:在`'1:来自任务。rb:12:在'new'任务中。rb:3:在'initialize'中:给出的参数数量错误,预期为0