This article mainly introduces a few Ruby tips to share, this article explains the code block sequence calls, mainly said that the array in blocks in the use, Hash#fetch, create code snippets and other tips, the need for friends can refer to the
Sequence calls to code blocks
The 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!"
The main is that the use of array in block
To remove an element from an array
The code is as follows:
>> args = [1, 2, 3]
>> a rest = args
>> A
=> 1
>> Rest
=> [2, 3]
It was just clear how the split sequence was used, and we didn't notice that we could easily get the rest of the sequence.
Hash#fetch
The 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 hashing is used, fetch may be more convenient than checking for the existence of a value.
To create a hash of a code snippet
The code is as follows:
>> smash = hash.new {|hash, key| hash[key] = "A #{key} just got smashed!"}
=> {}
>> smash[:p Lum] = "Cannot smash."
=> {:p lum=> "cannot smash."}
>> Smash[:watermelon]
=> {:p lum=> "cannot smash.",:watermelon=> "a watermelon just got smashed!"}
Using a snippet to produce a hash makes it easy to maintain some undefined initial values, especially in the Fibonacci calculations (I didn't see how to use them).
Array#sort_by
The code is as follows:
>> cars =%w[beetle Volt Camry]
=> ["Beetle", "Volt", "Camry"]
>> cars.sort_by {|car| car.size}
=> ["Volt", "Camry", "Beetle"]
The Sort_by method of the sequence is used to sort the return value of the code snippet, just as for the Symbol#to_proc map or sort
String#present?
The code is as follows:
>> "Brain". Present?
=> true
>> "". Present?
=> false
Rails developers may be familiar with blank, but what about present? It's also a good way to actually determine if the return value is correct.
Here I do think about the difference between find (: All) and see (: a) whether there is a return value. There is also a
. exists?
. Empty?
. Blank?
. Nil?
See more.