6

When I interpolate an array of strings, it includes the escape characters for the quotes '\"', how would I interpolate it sans quotes?

string_array = ["a","b","c"]
p "#{string_array}"        # => "[\"a\", \"b\", \"c\"]"
4
  • 1
    Use to_s instead? What is "sans quotes"? Commented May 24, 2013 at 20:35
  • 2
    @squiguy: String interpolation just calls to_s on the array, so he'd have the same result. "Sans quotes" means without the quotes. Commented May 24, 2013 at 20:37
  • In his case messick, the reason the backslashes are there, is because he has called inspect on a string, not string_array. The .inspect method for a string and array are different. (I think) Commented May 24, 2013 at 20:45
  • @messick I didn't know he wanted to join the elements, but yes you are correct. Commented May 24, 2013 at 20:50

2 Answers 2

6

using p "#{string_array}" is the same as puts "#{string_array}".inspect

Remember because p object is the same as puts object.inspect

which is the same as (in your case, you called p on a string):

puts string_array.to_s.inspect 

(to_s is always called whenever an array is asked by something to become a string (to be printed and whatnot.)

So you actually are inspecting the string that was returned by the array, not the array itself.

If you just wanted to print ["a", "b", "c"] the way to do that would to use p string_array not p "#{string_array}"

if you want to join all the strings in the array together, you would use String#join to do so. E.g. if i wanted to put a comma and a space in between each value, like messick, i would use:

puts string_array.join(", ")

This would output: "a, b, c"

Sign up to request clarification or add additional context in comments.

2 Comments

DOH! thanks for that detailed response. completely forgot p calls inspect. cheers!
NP! Glad I could help, remember to accept the answer if you are satisfied!
3

You need to join the array elements.

["a","b","c"].join(', ')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.