I was going through some piece of code when I found this line

if ('%{test}' % {:test => 'replaced'} == 'replaced')
  # If this works, we are all good to go.

Why is '%{test}' % {:test => 'replaced'} returning value "replaced"? What exactly is % doing over here?

有帮助吗?

解决方案

That is doing "interpolation". The value "replaced" of the key :test of the hash is inserted to the %{test} position in the original string '%{test}'.

The % can take a string, array, or hash depending on the need. When you only have a single slot in the template as in this case, it is better to use %s and pass a string like

"%s" % "replaced"

With the particular example, it is not useful.

It becomes useful when you want to replace a part of a string. For example, if you want to generate a series of strings:

"Hello World", "Hey World", "Bye World" 

you can have a template string s = "%s World" and interpolate things into it like

s % "Hello"
s % "Hey" 
s % "Bye"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top