String Things in Ruby

String alternatives in ruby

%Q

Alternative for double-quoted strings. Below are equivalent

1
2
3
name_of_object = "John"
puts %Q(Hello World #{name_of_object})
puts "Hello World John"

You could replace ( and ) with non-alphanumeric characters.

1
2
3
4
puts %Q!Hello World!
puts %Q[Hello World]
puts %Q+Hello World+
puts %/Hello World/ # you can use also.

%q

Alternative for single-quoted strings. But it can’t do expression substitution

1
puts %q(Hello World #{name_of_object}) # output: Hello World #{name_of_object}

%W

Used for double-quoted array.

1
2
world = "World"
%W(Hello #{world} John\ Smile) # output: ["Hello", "World", "John Smile"]

%w

Used for single-quoted array. No expression substitution

1
%w(Hello #{world} Good) # output: ["Hello", "#{world}", "Good"]

%s

Used for symbols. No expression substitution.

1
2
%s(foo) # output: :foo
%s(foo bar) # output: :"foo bar"

Comments