'bar' } => "foo = bar" so...">

Ruby% operator

I'm having trouble understanding what the following code snippet does

"foo = %{foo}" % { :foo => 'bar' }
=> "foo = bar"

so from the understanding that "foo =% {foo}" is a format specification, but in this case it seems to perform variable interpolation using the% {foo} function?

+4
source share
3 answers

String#% uses the given string as the format specification and applies the argument (array / hash) and returns the resulting string.

%{...}is a link to format the name. There also %<...>, who also need a formatting style (s, d, f, ...)

"foo = %{key}" % { :key => 'bar' }
# => "foo = bar"
"foo = %<key>s" % { :key => 'bar' }
# => "foo = bar"

See the format specification for details Kernel#sprintf.

+2
source

doc String#% refers to sprintf.

sprintf doc , ( -) ( ).

+2

- , (foo = %{foo}), % , % String (String #%), , . % , , , , key , , bar

, .

hash = { :key => 'bar' }
"foo = #{hash[:key]}" 

foo = "bar"
"foo = #{foo}"

, , .

+1

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


All Articles