It's been a month since I started learning with rails and Ruby. There are still many things I don't understand, so I'll post it as a record this time as well.
By the way, today, I used the symbol of "Introduction to Ruby to Become a Professional". A little while creating a unit conversion program? I summarized the symbols that became!
**-Symbols may be used instead of strings, but they are not necessarily the same objects as strings ** ** ・ The same symbol is the same object **
Is it roughly like this?
Also, as a way of defining,
: Symbol name : example => Can also be expressed as "example"
The big difference is ** Symbols are internally processed as integers and are immutable objects. Destructive changes do not work. ** **
Now that the basics have been reorganized, the next step is how to use them in hashes.
examples = { :a => "aaa", :b => "bbb", :c => "ccc"}
examples = {a: "aaa", b: "bbb", c: "ccc"} # Omitted form
call example [: a] => # "aaa"
All can be changed to symbols
examples = { :a => :aaa, :b => :bbb, :c => :ccc}
Symbols are suitable for hash keys, so they are usually expressed as "symbol: value". (Due to immutable properties, processing speed, etc.)
Finally, regarding the use of keyword arguments. Basically, there is no problem with "symbol: value" as above.
def example_length(length, from: :m, to: :m)
units = { m: 1.0, ft: 3.28, in: 39.37}
(length / units [from] * units [to]). round (2) # => units The to key is called like the value of the From key (m :) in the hash. end
As mentioned above, although it will be a mental point at the beginning of this book, it is the scariest thing to know, so In the future, I would like to keep moving my hands and organize the places I get caught in this way.
Recommended Posts