Strange string behavior in Ruby [duplicate] - ruby

This question already has answers here:
Where is Ruby's string literal juxtaposition feature officially documented?
(4 answers)
Closed 7 years ago.
So I was playing around in Ruby, and noticed that "a""b" returns "ab". If fond this very strange and useless, so I was wondering what this is called and if it has a purpose. I would appreciate any answers. Thanks!

This is called "string literal concatenation" and it is common in many languages. More specifically, adjacent string literals that are not separated by any other operators are automatically concatenated together. They may be considered to be just one string literal.
This exists in C, C++, Python, and Ruby to name a few.
MSDN: String Literal Concatenation (C)
Lexical Analysis: String literal concatenation (Python)
Where is Ruby's string literal juxtaposition feature officially documented? (Ruby)
Literals - Strings (Ruby)
An example of where this might be used is to break up a long string onto multiple lies, also adding the ability to comment each piece. Something I wrote in Python the other day:
hdr = struct.Struct('<'
'8s' # 0x00 Magic value
'I' # 0x08 Offset
'I' # 0x0C Length
'H' # 0x10 Type
'H' # 0x12 Flags
) # 0x14 (Total)
Note that this method takes just one parameter, a string, and I didn't manually concatenate the pieces.

I've never noticed this before, and this looks to be another form of concatenation like << and +.

Related

./prog.go:41:11: invalid character literal (more than one character) [duplicate]

This question already has an answer here:
more than one character in rune literal in go [closed]
(1 answer)
Closed 8 months ago.
I am new to Go language i just started learning by doing, but while running this code, im getting
the error as:
a./prog.go:41:11: invalid character literal (more than one character)
package main
import ("fmt")
func main() {
const NAME = "Michael"
const(
age int = 22
color = 'Fair'
)
fmt.Println(NAME)
fmt.Println(age)
fmt.Println(color)
}
In the above code, you are using single quotes for color variable value, that is what causing this error, try changing it to double quotes as below:
color = "Fair"
this should work.
(Not only) for Go, it can be a good exercise to have open the Go Reference Specification, as it is quite short and written for the language user. Here is what the official rules say about "runes" and "strings":
Rune Literals
A rune literal represents a rune constant, an integer value identifying a Unicode code point. A rune literal is expressed as one or more characters enclosed in single quotes, as in 'x' or '\n'.
For strings:
String Literals
[there are two types, raw and interpreted string literals!]
Raw string literals are character sequences between back quotes, as in `foo`. [...]
Interpreted string literals are character sequences between double quotes, as in "bar".
It can be handy to browse through the surrounding paragraphs to discover more rules and possible gotchas that one might encounter when coming from other languages.

Surprising string concatenation [duplicate]

This question already has answers here:
Where is Ruby's string literal juxtaposition feature officially documented?
(4 answers)
Closed 7 years ago.
I am surprised by some string concatenation I've stumbled upon in a codebase I support. Why, or how really, does the following manage to concatenate two strings together?
queue_name = 'gen-request-' "#{ENV['USERNAME'].gsub('.','')}"
=> "gen-request-robertkuhar"
I had expected to see a '+' between the two strings, but its not there. Is it implied or something?
I know this just makes more sense with up-the-middle string interpolation. Thats not what I'm asking. I want to know what it is about the language syntax that allows this to work in the first place.
This only works for string literals, and a part of the literal syntax.
If you have 2 string literals with just whitespace between them, they get turned into a single string. It's a convention borrowed from later versions of C.

Preventing converting string into octal number in Ruby

Assume we have following ruby code
require 'yaml'
h={"key"=>[{"step1"=>["0910","1223"]}]}
puts h.to_yaml
"0910" is a string
but after to_yaml conversion, string turns into octal number.
---
key:
- step1:
- 0910
- '1223'
the problem is I cannot change h variable. I receive it from outside, and I need to solve problem without changing it.
You are mistaken that there is an octal number in your YAML output. The YAML spec refers to octal on two occasions, and both clearly indicate that an octal number in a YAML file starts with 0o (which is a similar to what Ruby and newer versions of Python use for specifying octal; Python also dropped the support for 0 only octals in version 3, Ruby doesn't seem to have done that—yet).
The custom to indicate octal integers starting with a 0 only, has been proven confusing in many language and was dropped from the YAML specification six years ago. It might be that your parser still supports it, but it shouldn't.
In any case the characters 8 and 9 can never occur in an integer represented as an octal number, so in this case there can be no confusion that that unquoted scalar is a number.
The string 1223 could be interpreted as a normal integer, therefore it must always be represented as a quoted string scalar.
The interesting thing would be to see what happens when you dump the string "0708". If your YAML library is up-to-date with the spec (version 1.2) it can just dump this as an unquoted scalar. Because of the leading zero that is not followed by o (or x) there can be no confusion that this could be an octal number (resp. hexadecimal) either, but for compatibility with old parsers (from before 2009) your parser might just quote it to be on the safe side.
According the the YAML spec numbers prefixed with a 0 signal an octal base (as does in Ruby). However 08 is not a valid octal number, so it doesn't get quoted.
When you come to load this data from the YAML file, the data appears exactly as you need.
0> h={"key"=>[{"step1"=>["0910","1223"]}]}
=> {"key"=>[{"step1"=>["0910", "1223"]}]}
0> yaml_h = h.to_yaml
=> "---\nkey:\n- step1:\n - 0910\n - '1223'\n"
0> YAML.load(yaml_h)
=> {"key"=>[{"step1"=>["0910", "1223"]}]}
If you can't use the data in this state perhaps you could expand on the question and give more detail.
There was a similar task.
I use in secrets.yml:
processing_eth_address: "0x5774226def39e67d6afe6f735f9268d63db6031b"
OR
processing_eth_address: <%= "\'#{ENV["PROCESSING_ETH_ADDRESS"]}\'" %>
My Ruby doesn't do this octal conversion but I had a similar issue with dates. I used to_yaml(canonical: true) to get around this issue. It's more verbose but it's correct.
{"date_of_birth" => "1991-02-29"}.to_yaml
=> "---\ndate_of_birth: 1991-02-29\n"
{"date_of_birth" => "1991-02-29"}.to_yaml(canonical: true)
=> "---\n{\n ? \"date_of_birth\"\n : \"1991-02-29\",\n}\n"

Ruby << for String [duplicate]

This question already has answers here:
What are <-- Ruby Strings called? And how do I insert variables in them?
(3 answers)
Closed 8 years ago.
Can someone tell me the name of
<<-MAP
STRING HERE
MAP
operator (<<-) in ruby? I tried search for 'double less than' but it didn't turn up anything. I want to learn more about it but don't even know what it's called!
Thanks
Thats called the here doc syntax .Generally used to enter multiline strings. You can read about it here http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html
and also here The <<- operator on Ruby, where is it documented?
It's not an operator, it's a here document (aka heredoc) String literal. It works more or less like heredocs in other languages.
It is specified in section 8.7.6.3.6 of the ISO Ruby Language Specification.

Significance of colon : in Ruby [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Understanding Symbols In Ruby
What is the colon operator in Ruby?
I really feel naive asking this, but I'm going to go ahead and ask :
What is the importance of : in ruby ?
I have seen it being used in a number of places like params[:id] or like x < :length.
A colon denotes a "symbol". A symbol is like a string, but it is immutable (you can't change its contents). Behind the scenes, it also takes up less memory, since a symbol only needs to exist once in memory (i.e., two strings called "length" will exist twice in memory, but two symbols called :length will point to the same object).
:length means it is a Symbol
Symbols are Strings, just with an important difference, Symbols are immutable.
RubyDoc: Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods.
Here are some good places to learn more about symbols
The Ruby_Newbie Guide to Symbols
Understanding Ruby Symbols
The Difference Between Ruby Symbols and Strings
It is syntax indication of type for interpreter.
0-9 numeric*
: symbol
"" string
[] array
{} hash
Patterns more complicated in reality.

Resources