James Roberts
James Roberts

Reputation: 235

Ruby string structure

I am attempting to create a string using:

puts '["#{follower.screen_name}"]'

I want the output to be

["DailySanJose"]

where DailySanJose is the value of follower.screen_name. However, the current output is

["#{follower.screen_name}"]

Any help greatly appreciated.

Upvotes: 1

Views: 75

Answers (6)

Aaganja
Aaganja

Reputation: 552

You can use puts '["'+follower.screen_name+'"]'

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110755

To round out the options, you could also use a heredoc:

howdy = "hi"
puts <<_
["#{howdy}"]
_
  # ["hi"]

Upvotes: 0

tadman
tadman

Reputation: 211740

If you're trying to make something like JSON output:

require 'json'

test = "DailySanJose"

JSON.dump([ test ])
# => "[\"DailySanJose\"]"

The advantage here is this accounts for strings like The "Test" which requires double quoting. Don't be confused by the \" part, as when you print that it comes out exactly as-is:

puts JSON.dump([ test ])
# => ["DailySanJose"]

There's also a few other simple ways:

[ test ].inspect
# => "[\"DailySanJose\"]"

Upvotes: 1

Abdoo Dev
Abdoo Dev

Reputation: 1276

Edit

you can do it this way with double quotes

puts %{["#{follower.screen_name}"]}

Upvotes: -1

Stephen Carman
Stephen Carman

Reputation: 997

You could use a %Q to not have to worry about escaping quotes

such as

%Q(["#{follower.screen_name}"])

This will escape the quotes for you automatically and do the string interpolation, that way you don't have to worry about it yourself.

Upvotes: 3

Linuxios
Linuxios

Reputation: 35788

Interpolation (#{}) only works in double quoted strings.

Try this:

puts "[\"#{follower.screen_name}\"]"

I'm including the double quotes in the string by escaping them with the \ (backslash) character.

Upvotes: 4

Related Questions