Reputation: 2080
As I am going through some of the Ruby Doc's I have encountered percent strings, two of which I am a little confused about. Specifically it is the %()
string = %(I am a string)
#=> "I am a string"
and the %q()
string = %q(I am a string)
#=> "I am a string"
When I played with them they both seem to output a string the same as if I just wrote
string = "I am a string"
#=> "I am a string"
Why, and in what instances, would one prefer to use them as opposed to just creating a string literal, since they do not seem to save much by way of typing nor ease?
Upvotes: 4
Views: 1219
Reputation: 61885
The %
and %q
forms are string literals as well, just with different parsing rules. Consider:
%q(I am a 'string' with a "string" in me!)
Allowing the different forms, with different escape/termination characters, can make certain literals easier to express. I prefer '
-by-default, but it's about using an appropriate form for the given situation.
The %
(same as %Q
) and %q
forms have the same relationship as the "
and '
forms; so the difference between using one or the other (of the same family) should be clear.
Historically, these different % Notations were 'borrowed' from perl.
Upvotes: 5