ruby - 百分比运算符,字符串插值

标签 ruby

这是 Zed Shaw 书中的一些代码:

formatter = "%{first} %{second} %{third} %{fourth}"

puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
puts formatter % {first: "one", second: "two", third: "three", fourth: "four"}
puts formatter % {first: true, second: false, third: true, fourth: false}
puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter}

puts formatter % {
  first: "I had this thing.",
  second: "That you could type up right.",
  third: "But it didn't sing.",
  fourth: "So I said goodnight."
}

我理解%{}默认是%Q{},也就是字符串插值。但是双引号里面的%{}是什么意思呢?

"%{first} %{second} %{third} %{fourth}"

这行是什么意思?

puts formatter % {first: 1, second: 2, third: 3, fourth: 4}

最佳答案

两者都与 %Q 无关。

formatter 和 hash 之间的 %String#%方法。

"%{first} %{second} %{third} %{fourth}" 是格式字符串,参见 Kernel#sprintf了解详情。

关于ruby - 百分比运算符,字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556946/

相关文章:

ruby - 从不同的地方重新提出 ruby 异常

ruby - 大厨 Ruby 挖掘出错误的参数数量

ruby - NameError(未初始化常量 ActionDispatch::ExceptionWrapper):

ruby-on-rails - Actionmailer 不发送邮件,带 rails 3

ruby - 如何通过反射获取 Ruby 模块类定义的常量?

javascript - 单击 Rails 中的提交按钮时,如何在重定向到下一页之前显示模式?

ruby - 你如何在 Ruby 中初始化变量?

ruby - 期待(类)。接收(:new) syntax

ruby-on-rails - 如何分离功能和登录 ruby​​ 方法

ruby - 将字符串拆分为哈希?