Percent operator, line interpolation

Here is the code from Zed Shaw’s 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 %{} by default %Q{} , and this is string interpolation. But what is the value of %{} inside the double quote?

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

And what is the meaning of this line?

 puts formatter % {first: 1, second: 2, third: 3, fourth: 4} 
+6
source share
2 answers

None of them are associated with %Q

% between formatter and hash is String#% method.

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

+7
source

Just correct the original answer a bit.

Common usage of sprintf ( String#% ) expects the values ​​to be presented in the same sequence as the format codes in the format string. The first value following the format string is used for the first substitution, the second value is used for the second substitution, etc.

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

Ruby also supports link by name in format strings. To format the replacement value, use the form %<name>s . This form expects a formatting code following > . The order of values ​​(i.e., in the hash) does not determine where the values ​​are used. The same value can be used more than once.

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

If you do not want to format the replacement value, you can use the form %{name} , which does not expect code formatting. Everything that follows } is considered a literal, not a formatting code.

 sprintf("%<foo>s", { :foo => 456 }) => "456" sprintf("%{foo} : %{foo}s", { :bar => 123, :foo => 456 }) => "456 : 456s" 
+7
source

Source: https://habr.com/ru/post/982584/


All Articles