Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Percent operator, string interpolation

Tags:

ruby

Here's some code from Zed Shaw book :

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."
}

I understand that %{} is %Q{} by default, and that is string interpolation. But what is the meaning of %{} inside double quote?

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

And what is the meaning of this line?

puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
like image 896
zerozero7 Avatar asked Feb 17 '15 07:02

zerozero7


1 Answers

Neither are related to %Q.

The % between formatter and the hash is the String#% method.

"%{first} %{second} %{third} %{fourth}" is a format string, see Kernel#sprintf for details.

like image 74
Yu Hao Avatar answered Sep 30 '22 15:09

Yu Hao