简体   繁体   中英

Ruby, Interpolating an Array of Strings

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\"]"

您需要join数组元素。

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

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. Eg 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM