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

时间:2015-02-17 07:41:50

标签: 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}

2 个答案:

答案 0 :(得分:16)

两者都与%Q无关。

%与散列之间的formatterString#%方法。

"%{first} %{second} %{third} %{fourth}"是格式字符串,有关详细信息,请参阅Kernel#sprintf

答案 1 :(得分:10)

只是为了扩大原来的答案。

sprintfString#%)的常见用法要求以与格式字符串中的格式代码相同的顺序提供值。格式字符串后面的第一个值用于第一次替换,第二个值用于第二次替换,等等。

sprintf("%d : %f : %d", 123, 456, 789)
=> "123 : 456.000000 : 789"

Ruby还支持格式字符串中的名称引用。要格式化替换值,请使用表单%<name>s。此表单需要>之后的格式代码。值的顺序(即,在散列中)不确定值的使用位置。相同的值可以多次使用。

sprintf("%<foo>d : %<bar>f : %<bar>d", { :bar => 123, :foo => 456 })
=> "456 : 123.000000 : 123"

如果您不想格式化替换值,可以使用%{name}形式,它不需要格式化代码。 <{1}}之后的任何内容都被视为文字而非格式代码。

}