Ruby Single and Double Quotes

Double vs single quotes

" " allows you to do string interpolation, e.g.:

world_type = 'Mars'
"Hello #{world_type}"

Ruby single and double quotes

In Ruby, double quotes are interpolated, meaning the code in #{} is evaluated as Ruby. Single quotes are treated as literals (meaning the code isn't evaluated).

var = "hello"
"#{var} world" #=> "hello world"
'#{var} world' #=> "#{var} world"

For some extra-special magic, Ruby also offers another way to create strings:

%Q() # behaves like double quotes
%q() # behaves like single quotes

For example:

%Q(#{var} world) #=> "hello world"
%q(#{var} world) #=> "#{var} world"

Ruby - what's the difference between single and double quotes?

Yes, single-quoted strings don't process ASCII escape codes and they don't do string interpolation.

name = 'Joe'
greeting = 'Hello, #{name}' # this won't produce "Hello, Joe"

ruby on rails replace single-quotes with double-quote in a string

If that's the only case you're covering where you need to show some output in double quoted string then. How about something simple like following

str = "The result of the child is \"#{current_res}\" and the lowest grade is \"#{lowest_res }\" ."

You can escape quotes in double quoted strings.

Both single and double quotes in a ruby array

a = ["Customer name", "Address", "Qualification"]
a.map { |i| "'#{i}'" } # => ["'Customer name'", "'Address'", "'Qualification'"]

When to use single vs. double quotes in a Rails app

The difference between using double quotes versus single quotes is that double quotes interpret escaped characters and single quotes preserve them.

Here is an example

 puts "i \n love \n ruby"
#i
#love
#ruby

and

 puts 'i \n love \n ruby'
#i \n love \n ruby

Difference between double quotes and single quotes in Ruby

Double-quotes interpolates.

Single-quotes do not, e.g.,

puts "Hi #{42+5}"
=> "Hi 47"

puts 'Hi #{42+5}'
=> "Hi #{42+5}"


Related Topics



Leave a reply



Submit