What does "" (two double quotes) do in Ruby? - ruby

I've seen Ruby code in which there are only two double quotes ("") on a line. What does that line do?

I assume you might have seen a code like this.
def some_method
#do some operations
""
end
In this context, it means that the method is returning an empty string. In Ruby, the last evaluated operation in a method is what is returned from that method. So in this case, it returns an empty string literal.

Two double quotes represent an literal empty string in Ruby. And in many other languages.

Related

Single backslash for Ruby gsub replacement value?

Does anyone know how to provide a single backslash as the replacement value in Ruby's gsub method? I thought using double backslashes for the replacement value would result in a single backslash but it results in two backslashes.
Example: "a\b".gsub("\", "\\")
Result: a\\b
I also get the same result using a block:
Example: "a\b".gsub("\"){"\\"}
Result: a\\b
Obviously I can't use a single backslash for the replacement value since that would just serve to escape the quote that follows it. I've also tried using single (as opposed to double) quotes around the replacement value but still get two backslashes in the result.
EDIT: Thanks to the commenters I now realize my confusion was with how the Rails console reports the result of the operation (i.e. a\\b). Although the strings 'a\b' and 'a\\b' appear to be different, they both have the same length:
'a\b'.length (3)
'a\\b'.length (3)
You can represent a single backslash by either "\\" or '\\'. Try this in irb, where
"\\".size
correctly outputs 1, showing that you indeed have only one character in this string, not 2 as you think. You can also do a
puts "\\"
Similarily, your example
puts("a\b".gsub("\", "\\"))
correctly prints
a\b

Remove quotation marks from an object

I want to call User.first, but I get it like "User.first". How can I strip the quotation marks so I can call User? Using a regex like this: gsub!(/\A"|"\Z/, "") returns nil instead of the expression.
First I would say that it's dangerous to do this based on where your input is coming from, but if you absolutely need to run arbitrary ruby code contained in a string, you would use eval:
http://ruby-doc.org/core-2.2.2/Kernel.html#method-i-eval
Again, I would avoid evaluating strings if at all possible.

Meaning of #{ } in Ruby?

The operation #{ } appears to be so fundamental that my Ruby book completely skips its definition. Can someone provide an explanation?
Why This Is a Good Question
This is a tough question to Google for unless you know the right search terms. The #{} operator technically performs expression substitution inside a string literal.
The Answer
The #{} literal is the operator used for interpolation inside double-quoted strings the same way that the backticks or $() construct would be used in Bash. From a practical point of view, the expression inside the literal is evaluated, and then the entire #{} expression (including both the operator and the expression it contains) is replaced in situ with the result.
Related Links
http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#string
http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#Interpolation
Ruby (on Rails) syntax
It allows you to put Ruby code within a string. So:
"three plus three is #{3+3}"
Would output:
"three plus three is 6"
It's commonly used to insert variable values into strings without having to mess around with string concatenation:
"Your username is #{user}"
It's the string interpolation operator, you use it to insert an expression into a string.
Your string needs to be embedded in " to let this magic work, no 's.
It is much faster and better than string concatenation.
var = "variable"
"this is a string with a #{var} in" => "this is a string with a variable in"

Why are empty Arrays and Hashes treated differently when cast to string and then to symbol?

In Ruby, why are these two operations different for empty Arrays and Hashes?
Empty Array:
[].to_s.to_sym => :[]
Empty Hash:
{}.to_s.to_sym => :"{}"
They aren't really different, it's just that they're displayed differently. The { character can't be the start of a symbol, so it's enclosed in quote marks. It's the same thing you'd do if you wanted to create a symbol that had a - in it, since otherwise it would be interpreted as the subtraction operator. In fact, you can go into IRB and test that the quotes don't really affect the symbol.
:[] == :"[]" #=> true
So, basically, one is able to use a shorter form, and the other has to be more verbose so that the parser can understand it. But there's not an essential difference in the meaning or form of the two.
Because string representation of [] is "[]" and string representation of {} is "{}". By the way, :[] is equal to :"[]". The difference is that you can write symbol :"[]" without parenthesis, but you can't do it for :"{}", Ruby syntax disallow that.

What does %{} do in Ruby?

In Matt's post about drying up cucumber tests, Aslak suggests the following.
When I have lots of quotes, I prefer this:
Given %{I enter “#{User.first.username}” in “username”}
What is the %{CONTENT} construct called? Will someone mind referencing it in some documentation? I'm not sure how to go about looking it up.
There's also the stuff about %Q. Is that equivalent to just %? What of the curly braces? Can you use square braces? Do they function differently?
Finally, what is the #{<ruby stuff to be evaluated>} construct called? Is there a reference to that in documentation somewhere, too?
None of the other answers actually answer the question.
This is percent sign notation. The percent sign indicates that the next character is a literal delimiter, and you can use any (non alphanumeric) one you want. For example:
%{stuff}
%[stuff]
%?stuff?
etc. This allows you to put double quotes, single quotes etc into the string without escaping:
%{foo='bar with embedded "baz"'}
returns the literal string:
foo='bar with embedded "baz"'
The percent sign can be followed by a letter modifier to determine how the string is interpolated. For example, %Q[ ] is an interpolated String, %q[ ] is a non-interpolated String, %i[ ] is a non-interpolated Array of Symbols etc. So for example:
%i#potato tuna#
returns this array of Symbols:
[:potato, :tuna]
Details are here: Wikibooks
"Percent literals" is usually a good way to google some information:
http://www.sampierson.com/articles/ruby-percent-literals
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation
#{} is called "string interpolation".
The #{1+1} is called String Interpolation.
I, and Wikibooks, refer to the % stuff as just "% notation". Reference here. The % notation takes any delimiter, so long as it's non alphanumeric. It can also take modifiers (kind of like how regular expressions take options), one of which, interestingly enough, is whether you'll permit #{}-style string interpolation (this is also enabled by default).
% then does some special stuff to it, giving that notation some distinct, if a bit cryptic to beginners, terseness. For example %w{hello world} returns an array ['hello','world']. %s{hello} returns a symbol :hello.

Resources