Meaning of #{ } in Ruby? - 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"

Related

Find exact word in string and not partial

I have the following string
str = "feminino blue"
I need to know if there is a string called "mini" inside this string.
When I use include? method, the return is true because "feMINino" has "min"
Is there a way to search for the exact word that is passed as param?
Thanks
Sounds like a use case for regular expressions, which can match all kinds of more complex string patterns. You can read through that page for all the specifics (and it's very valuable to learn, not just as a Ruby concept; Regexes are used in almost every modern language), but this should cover your use case.
/\bmini\b/ =~ str
\b means "match a word boundary", so exactly one of the things to the left or right should be a word character and the other side should not (i.e. should be whitespace or the beginning/end of the string).
This will return nil if there's no match or the index of the match if there is one. Since nil is falsy and all numbers are truthy, this return value is safe to use in an if statement if all you need is a yes/no answer.
If the string you're working with is not constant and is instead in a variable called, say, my_word, you can interpolate it.
/\b#{Regexp.quote(my_word)}\b/ =~ str

Using a ruby regular expression

I'm completely new to Ruby so I was just wondering if someone could help me out.
I have the following String:
"<planKey><key>OR-J8U</key></planKey>"
What is the regex I have to write to get the center part OR-J8U?
Use the following:
str = "<planKey><key>OR-J8U</key></planKey>"
str[/(?<=\<key\>).*(?=\<\/key\>)/]
#=> "OR-J8U"
This captures anything in between opening and closing 'key' tags using lookahead and lookbehinds
If you want to get the string OR-J8U then you could simply use that string in the regular expression; the - character has to be escaped:
/OR\-J8U/
Though, I believe you want any string that is enclosed within <planKey><key> and </key></planKey>. In that case ice's answer is useful if you allow for an empty string:
/(?<=\<key\>).*(?=\<\/key\>)/
If you don't allow for an empty string, replace the * with +:
/(?<=\<key\>).*(?=\<\/key\>)/
If you prefer a more general approach (any string enclosed within any tags), then I believe the common opinion is not to use a regular expression. Instead consider using an HTML parser. On SO you can find some questions and answers in that regard.

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.

How can I remove the string "\n" from within a Ruby string?

I have this string:
"some text\nandsomemore"
I need to remove the "\n" from it. I've tried
"some text\nandsomemore".gsub('\n','')
but it doesn't work. How do I do it? Thanks for reading.
You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.
Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.
While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.
In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.
See here for more info
If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip method.
" hello ".strip #=> "hello"
"\tgoodbye\r\n".strip #=> "goodbye"
as mentioned here.
edit The original title for this question was different. My answer is for the original question.
When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:
x = "foo\nfoo"
x.delete!("\n")
x now equals "foofoo"
In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.
You don't need a regex for this. Use tr:
"some text\nandsomemore".tr("\n","")
use chomp or strip functions from Ruby:
"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"

What does "" (two double quotes) do in 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.

Resources