In ruby using a single quote is faster than double quotes as we can see in the message : Is there a performance gain in using single quotes vs double quotes in ruby?.
So why does everyone use double quotes (or both)???
Some examples :
https://github.com/rails/rails/blob/master/activerecord/test/models/company.rb
https://github.com/sinatra/sinatra/blob/master/test/routing_test.rb
https://github.com/jnicklas/capybara/blob/master/spec/rack_test_spec.rb
(I know, it's not everyone but the majority.)
EDIT 1 : Interpolation is not a reason!
Double quotes are not always with interpolation or anything special like this, in Sinatra :
it "defines HEAD request handlers with HEAD" do
Double quotes allows you to do interpolation : "Number of users : #{#count_user}"
Plus taking a look at the benchmarks, I'd say that at best it doesn't matter, the overhead is very small, and some benchmarks are actually faster with double quotes ...
Double quotes allow for string interpolation, single quotes will not evaluate anything within them while the double quotes will. For example, the double quotes will allow you to have escape characters and single quotes won't!
"he said \n hello"
will result in 2 lines while
'he said \n hello'
will result in a string with '\n' in the middle of it
One reason is that string interpolation is supported in double quotes but not single quotes.
For example:
some_var = 15
"I have #{some_var} cats"
# => "I have 15 cats"
'I have #{some_var} cats"
# => "I have \#{some_var} cats"
I personally prefer single quotes when possible because I think they look cleaner. But string interpolation is one very important reason to use double quotes.
With respect to the performance issue, it's so negligible that it's really a matter of preference rather than performance.
I don't know if you actually read that thread properly but #zetetic actually found that using double quotes is slightly faster. Nonetheless this test was done over 1 million assignments and thus in that regard they'r both basically the same speed.
It all comes down to preference. A lot of people come from languages where single quotation are just not possible and so they are used to double quotations. Its all a matter of preference.
It's been answered and accepted, and some of these are repeating others, but my 2¢ worth.
Using double quotes means that if you ever do want to add something that needs interpolation into a string later, you can just do so without having to change the quotes.
Consistency between strings that do require interpolation and those that don't.
Being able to include all English in a string, eg. "don't", "Jim's" without having to escape it, or change the quotes.
Embedding \ escape chars in strings like \n and \t
Related
I just have a general question.
Is there any difference using single and double quote marks within Lua?
Example:
require('test.lua')
require("test.lua")
When I programmed in PAWN, a language similar to C, single quote marks could be used for characters, but not strings of text, you had to use double quote marks for them.
And if there is no difference, which one is recommended to be used?
This question has most likely been answered already, however I failed to find a topic already answered.
Thank you.
Nope. No difference, except that you can enclose the other inside the ones that you are using.
-- No difference between these
myStr = "Hi!!"
myStr = 'Hi!!'
myStr = [[Hi!!]] -- The 'weird' way to make a string literal IMO...
-- Double quotes enclosed in single quotes
myStr = 'My friend said: "Hi!!"'
-- Single quotes enclosed in double quotes
myStr = "My friend said: 'Hi!!'"
-- Single and double quotes enclosed in double brackets
myStr = [[My friend said: "What's up?"]]
See: Strings in Lua for more information.
There is no difference between the two in Lua, so you can use whichever you like. I tend to differentiate between them semantically:
I use "double quotes" for user-visible strings and text, basically whatever appears on the output or in files
I use 'single quotes' for option-like strings for passing to methods and generally in code, like io.stdout:setvbuf('no')
You can find out about Lua strings easily enough by searching the internet for "lua strings".
Here is one result: http://www.lua.org/pil/2.4.html
You are free to choose your own quote style, as it makes no difference, but you should be consistent so that your code is nicer to read.
As a matter of preference, I would normally use double-quotes because Lua uses C-style escape-codes. Many script languages (Perl, for example) and command shells do make the distinction between single- and double-quoted strings, and it would be nice to be a little consistent with these quasi-standard practices.
I mean that when I see a single-quoted string I have to actually think about what language I'm reading, and whether or not escape-codes are substituted in that string. With double-quoted strings I don't have to think about it, because as a general rule any language that substitutes C-style escape-codes in a string will do that in a double-quoted string.
I'm internationalizing an application and cannot figure out how to declare a translation string that contains both single and double quotes. Here's an example of the en.yml string that I am trying to
en:
my_string: When you're using double quotes, they look like "this"
With the above string, I get the following error:
can not load translations from /vagrant/config/locales/en.yml,
expected it to return a hash, but does not
If there were just double quotes, I would wrap it in single quotes and vise-versa. How do I handle both double and single quotes though?
escaping should be done like this
"When you're using double quotes, they look like \"this\""
Actually I can’t figure out why do you need obsolete typewriter quotes in translation strings. There is 2013 around and we are not stuck to ASCII-7 anymore. The typography rules dictate their demands to use unicode quotation marks.
That’s the best practice ever: map those within 3rd keyboard level (or, eventually, sed your yml):
"When you’re using double quotes, they look like “this”"
With such an approach you’ll never run into troubles with escaping and your clients will definitely say “oh, neat.”
Sorry, if this seems a little bit off-topic, but since the question was about translation strings, I still consider it to be the best solution.
See if this works for you, it works perfectly for me in my spring boot applications where I needed to pass JSON values in:
Using YAML pipe style:
app.json:
values: |
{"key": "value"}
Your case would be:
en:
my_string: |
When you're using double quotes, they look like "this"
Folded style might work too but I haven't tried.
See more here: http://symfony.com/doc/current/components/yaml/yaml_format.html#strings
I understand the functional difference between single and double quotes in Ruby, but I'm wondering what concrete reasons people have for varying between the two. In my mind it seems like you should just always use a double quote, and not think about it.
A couple rationales that I've read in researching the topic...
Use a single quote unless a double quote is required.
There's a very, very minor performance advantage to a single quotes.
Any other interesting thoughts out there? (Or maybe this is a case of the freedom or Ruby leaving the door open for no One Right Way to do something...)
I usually follow the following rule:
never use double quotes (or %Q or %W) if you don't interpolate
The reason for this is that if you're trying to track down an error or a security bug, you immediately know when looking at the beginning of the string that there cannot possibly any code inside it, therefore the bug cannot be in there.
However, I also follow the following exception to the rule:
use double quotes if they make the code more readable
I.e. I prefer
"It's time"
over
'It\'s time'
%q{It's time}
It is technically true that single quoted strings are infinitesimally faster to parse than double quoted strings, but that's irrelevant because
the program only gets parsed once, during startup, there is no difference in runtime performance
the performance difference really is extremely small
the time taken to parse strings is irrelevant compared to the time taken to parse some of Ruby's crazier syntax
So, the answer to your question is: Yes, there is an advantage, namely that you can spot right away whether or not a string may contain code.
I can think of three reasons to use single quoted strings:
They look cleaner (the reason I use them)
They make it easier to create a string you'd otherwise have to escape ('he said "yes"' vs "he said \"yes\"")
They are slightly more performant.
I would assume using a single-quoted string is faster, since double quotes allow string interpolation, and single-quoted strings do not.
That's the only difference I know of. For that reason, it's probably best to only use a single-quoted string unless you need string interpolation:
num = 59
"I ate #{num} pineapples"`
Well, there are a lot of fuzz about the "performance gain" of single quoted strings vs double quoted strings.
The fact is that it doesn't really matter if you don't interpolate. There are a lot of benchmarks around the web that corroborate that assertion. (Some here at stackoverflow)
Personally, I use double for strings that have interpolation just for the sake of readability. I prefer to see the double quotes when I need them. But in fact there are methods in ruby for interpolating strings other than "double quoting" them:
%q{#{this} doesn't get interpolated}
%Q{#{this} is interpolated}
1.9.2-p290 :004 > x = 3
=> 3
1.9.2-p290 :005 > "#{x}"
=> "3"
1.9.2-p290 :006 > '#{x}'
=> "\#{x}"
In any other case, i prefer single quotes, because it's easier to type and just makes the code less overbloated to my eyes.
Since asking this question I've discovered this unofficial Ruby Style Guide that addresses this, and many many more styling questions I've had floating around in my head. I'd highly recommend checking it out.
I found that when putting variables in a string using #{} did not work in single quotes, but did work in double quotes as below.
comp_filnam and num (integer) are the variables I used to create the file name in the file path:
file_path_1 = "C:/CompanyData/Components/#{comp_filnam}#{num.to_s}.skp"
I'm very new to yaml, and I just want to know what I can and can't store character wise in yaml?
What are the escape characters for double quotes etc?
Can I span multiple lines?
Basically, you can store everything. Quotes aren't an issue, you can type text out without quotes (and for non-printable characters that you can't incorporate casually, there are the usual escape sequences). That means purely numerical text is considered a number, though - but then again, you can add quotes or an explicit type annotation (and I assume most libraries do that when necessary), e.g. !!str 100. Also, if you want to include the comment sign (#), you have to add quotes.
Another issue is that some strings may look like more complex YAML (e.g. certain uses of exclamation signs look like casts and certain uses of colons look like singleton associative tables). You can avoid these by using "multi-line" strings that just consist of a single line. Multi-line strings exist and come in two flavors, preserving linebreaks (--- |) and ignoring newlines except for blank lines (--- >, much like markdown).
In designing of a (mini)language:
When there are certain characters that should be escaped to lose special meanings (like quotes in some programming languages), what should be done, especially from a security perspective, when characters that are not escapable (e.g. normal characters which never have special meaning) are escaped? Should an error be "error"ed, or should the character be discarded, or should it be in the output the same as if it was not escaped?
Example:
In a simple language where strings are delimited by double-quotes("), and any quotes in a given string are escaped with a back-slash(\): for input "We \said, \"We want Moshiach Now\"" -- what would should be done with the letter s in said which is escaped?
I prefer the lexer to whine when this occurs. A lexer/parser should be tight about syntax; one can always loosen it up later. If you are sloppy, you'll find you can't retract a decision you didn't think you made.
Assume that you initially decide to treat " backslash not-an-escape " as that pair of characters, and the "T" is
not-an-escape today. Sometime later you decide to extend the language, and want "\T" to mean something special, and you change your language.
You'll find an angry mob of programmers storming your design castle,
because for them, "\T" means "\" "T" (or "T" depending on your default decision),
and you just broke their code. You hang your head in shame, retract the decision,
and then realize... oops, there are no more available escape characters!
This lesson goes for any piece of syntax that isn't well defined in your language. If it isn't explicitly legal, it should be implicitly illegal and your compiler should check it. Or you'll never be able to extend your successful language.
If your language isn't going to be successful, you may not care as much.
Well, one way to solve the problem is for the backslash to just mean backslash when it precedes a non-escapable character. That's what Python does:
>>> print "a\tb"
a b
>>> print "a\tb\Rc"
a b\Rc
Obviously, most systems take the escape character to mean "take the next character verbatim", so escaping a "non-escapable" character is usually harmless. The problem later happens when you get to comparisons and such, where the literal text does not represent the actual value (that's where you see a lot of issues securitywise, especially with things like URLs).
So on the one hand, you can only accept a limited number of escaped characters. In that sense, you have an "escape sequence", rather than an escaped character (the \x is the entire sequence rather than a \ followed by an x). That's like the most safe mechanism, and it's not really burdensome to write.
The other option is to ensure that you you "canonicalizing" everything you compare, through some ruleset. This typically means removing all of the escape sequences properly up front, before comparison and comparing only the final values rather than the literals.
Most systems interpret the slash as Will Hartung says, except for alphanumerics which are variously used as aliases for control codes, character classes, word boundaries, the start of hex sequences, case region markers, hex or octal digits, etc. \s in particular often means white-space in perl5 style regexs. JavaScript, which interprets it as 's' in one context and as whitespace in another suffers from subtle bugs because of this choice. Consider /foo\sbar/ vs new RegExp('foo\sbar').