How can i include a double quote in a string

i need to a include a double quote in a string without it being escaped.
For example

astring=“first few characters”
bstring=“last characters”

When i tried
newstring = astring + ‘"’ + bstring + ‘"’

newstring ended up as ‘first few characters"last characters"’

What trick can i use to obtain a string ‘first few characters “last
characters”’ out of the 2 string variables. That is for ruby not to
escaped the double quote.

Thanks in advance.

What trick can i use to obtain a string ‘first few characters “last
characters”’ out of the 2 string variables. That is for ruby not to
escaped the double quote.

Thanks in advance.

irb> newstring
=> “first few characters"last characters”"
irb> puts newstring
first few characters"last characters"
=> nil

The quotation marks aren’t actually escaped, they’re just shown that
way on inspection to differentiate them from the quotation marks
delimiting the entire string.

On Wed, Dec 29, 2010 at 6:31 PM, Rick T. [email protected] wrote:

What trick can i use to obtain a string ‘first few characters “last
characters”’ out of the 2 string variables. That is for ruby not to
escaped the double quote.

Thanks in advance.


Posted via http://www.ruby-forum.com/.

I assume you are doing this in irb, and looking at the result. If that
is
the case, irb inspects whatever it receves, since it receives a string
with
quotes in it, to display a string, it wraps the string in quotes. Thus
it
has to differentiate the internal quotes from the external, and escapes
them
before displaying the result to you. However, they are not actually
escaped, only displayed that way by some types of displaying. Try
printing
it out and you will see. Here are five ways to do this, I think either
the
first one, or %Q are the best, because they are easiest to read / most
straightforward…

a = “first”
b = “last”

[ “"#{a}" #{b}” ,
‘"’ + a + '" ’ + b,
‘"’ << a << '" ’ << b,
%Q(“#{a}” #{b}),
<<-ENDOFSTRING.strip,
“#{a}” #{b}
ENDOFSTRING
].each do |str|
puts “normal: #{str}”
puts “inspected: #{str.inspect}”
puts
end

Rick T. wrote in post #971378:

i need to a include a double quote in a string without it being escaped.
For example

astring=“first few characters”
bstring=“last characters”

When i tried
newstring = astring + ‘"’ + bstring + ‘"’

newstring ended up as ‘first few characters"last characters"’

$ irb --simple-prompt

a = “foo” + ‘"’ + “bar”
=> “foo"bar”

puts a
foo"bar << NOTE
=> nil

puts a.size
7 << NOTE
=> nil

So the string is 7 characters: f o o " b a r

irb uses #inspect to display the value of each expression you type.
String#inspect escapes double-quotes, so that the value is a valid
string literal (i.e. could be pasted back in to Ruby)