Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Single versus Double Quotes

Is there some sort of Ruby to_s method that changes a variable to a single-quoted string instead of double quotes?

Say I have

date = Time.now
date.to_s

and I want the output to be '2012-08-01 22:00:15'. How do I go about doing this? Or is there a method to convert "" strings to '' strings?

Thanks!

EDIT - More Detail

I'm using Rails to display some data in a database. I've created the @instanceVar as an array of arrays from my Controller/Model.

<% outer = [] %>
<% inner = [] %>

<% @instanceVar.each do |events| %>
  <% events.each do |event| %>
    <% inner << [event.date, event.total] %>
  <% end %>
  <% outer << inner %>
<% end %>

I need event.date to be a single quoted string.

    <% inner << ['event.date', event.total] %>

just literally adds the words event.date to the array, and

    <% inner << ["#{event.date}", event.total] %>

puts the date in double quotes.

EDIT2

<script>
  $.jqplot('trendingEvents', <%= outer %>,
  {
    #options go here
  });
</script>
like image 617
XML Slayer Avatar asked Aug 02 '12 21:08

XML Slayer


2 Answers

Strings are strings in ruby. They are all equal. The only difference is how you declare them (single quotes, double quotes, here-docs and maybe something else). Once you've got a string value in a variable, it doesn't matter how it was declared.

s1 = 'single quoted'
s1 # => "single quoted"

So, if your strings don't leave the rubyland (that is, you don't render them as javascript or whatever), you shouldn't worry about the quotes.

Response to edit 2

It seems that you have to build your json object in a more manual manner, rather than relying on default behaviour of Array#to_s

To emit ruby string as javascript single-quoted string literal you can do something like this:

<script type="text/javascript">
  var s = '<%= ruby_string %>';
</script>

<%= %> construct will render passed string without quotes. You supply the quotes yourself.

like image 194
Sergio Tulentsev Avatar answered Sep 22 '22 01:09

Sergio Tulentsev


Double-quotes as a string constructor allow you to interpolate variables. Single quotes are for literals. As mentioned, a string is a string once instantiated, displaying quotes is better left to the caller.

like image 21
jodell Avatar answered Sep 21 '22 01:09

jodell