A few Ruby tips and Ruby tips
Sequential call of code blocks
Copy codeThe Code is as follows:
Def touch_down
Yield [3, 7]
Puts "touchdown! "
End
Touch_down do | (first_down, second_down) |
Puts "# {first_down} yards on the run"
Puts "# {second_down} yards passed"
End
=> "3 yards on the run"
=> "7 yards passed"
=> "Touchdown! "
It mainly refers to the use of array in block
Retrieve elements from array
Copy codeThe Code is as follows:
> Args = [1, 2, 3]
> First, rest = args
> First
=> 1
> Rest
=> [2, 3]
Previously, we only knew how to use the split sequence, but did not notice that we can easily obtain the rest sequence.
Hash # fetch
Copy codeThe Code is as follows:
>>Items ={: apples => 2,: oranges => 3}
=> Items = {: apples => 2,: oranges => 3}
> Items. fetch (: apples)
=> 2
> Items. fetch (: bananas) {| key | "We don't carry # {key }! "}
=> We don't carry bananas!
When using hash, fetch may be easier than checking whether there are values.
Create a hash of a code segment
Copy codeThe Code is as follows:
> Smash = Hash. new {| hash, key | hash [key] = "a # {key} just got SMASHED! "}
=> {}
> Smash [: plum] = "cannot smash ."
==>{: Plum => "cannot smash ."}
> Smash [: watermelon]
==>{: Plum => "cannot smash.",: watermelon => "a watermelon just got SMASHED! "}
Using code segments to produce hashes can easily retain some undefined initial values, especially in Fibonacci calculations (I didn't see how to use them)
Array # sort_by
Copy codeThe Code is as follows:
> Cars = % w [beetle volt camry]
=> ["Beetle", "volt", "camry"]
> Cars. sort_by {| car. size}
=> ["Volt", "camry", "beetle"]
The sort_by method of the sequence is used to sort the return values of the code snippet, just like map or sort for Symbol # to_proc.
String # present?
Copy codeThe Code is as follows:
> "Brain". present?
=> True
> "". Present?
=> False
Rails developers may be interested in blank? Familiar, but what about present? In fact, it is a good way to determine whether the returned value is correct.
Here I do think of it. The difference between the values of find (: all) and find (: first) for the returned values is different. There is another
. Exists?
. Empty?
. Blank?
. Nil?
See more