Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\"]"
like image 942
user1297102 Avatar asked May 24 '13 20:05

user1297102


People also ask

What is string interpolation in Ruby?

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.

Can an array be interpolated?

Arrays can be interpolated by means of a one-to-one mapping given by (7) f : A S → A ¯ S , where is a sector.

Are strings arrays in Ruby?

With a Ruby string array, we can store many strings together. We often prefer iterators, not loops, to access an array's individual elements. In Ruby programs, we use string arrays in many places.

What does #{} do in Ruby?

In Ruby, string interpolation refers to the ability of double-quoted strings to execute Ruby code and replace portions of that strings (denoted by #{ ... }) with the evaluation of that Ruby code.


2 Answers

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"

like image 137
Senjai Avatar answered Nov 03 '22 20:11

Senjai


You need to join the array elements.

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

like image 31
Nick Messick Avatar answered Nov 03 '22 20:11

Nick Messick