SoFunction
Updated on 2025-04-07

A few Ruby tips to share

Sequence calls of code blocks

Copy the 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!" 

Mainly speaking, the use of array in block

Take out elements from array

Copy the codeThe code is as follows:

>> args = [1, 2, 3] 
>> first, rest = args 
 
>> first 
=> 1 
 
>> rest 
=> [2, 3] 

I just knew the usage of split sequences before, but I didn't notice that in fact, we can easily get the remaining sequences.

Hash#fetch

Copy the codeThe code is as follows:

>> items = { :apples => 2, :oranges => 3 } 
=> items = {:apples=>2, :oranges=>3} 
 
>> (:apples) 
=> 2 
 
>> (:bananas) { |key| "We don't carry #{key}!"} 
=> We don't carry bananas! 

When using hash, fetch may be more convenient than checking whether there are values.

Create a hash of a snippet

Copy the codeThe code is as follows:

>> smash = { |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 snippets for production hashs can easily maintain some undefined initial values, especially in Fibonacci calculations (I don't see how to use them)

Array#sort_by

Copy the codeThe code is as follows:

>> cars = %w[beetle volt camry] 
=> ["beetle", "volt", "camry"] 
 
>> cars.sort_by { |car| } 
=> ["volt", "camry", "beetle"] 

The sort_by method of the sequence is used to sort the return value of the code segment, just like map or sort for Symbol#to_proc

String#present?

Copy the codeThe code is as follows:

>> "brain".present? 
=> true 
 
>> "".present? 
=> false 

Rails developers might be for blank? More familiar, but what about present? In fact, it is also a very useful method to determine whether the return value is correct.

Here I do remember that there is a difference in judging whether there is a return value between find(:all) and find(:first). There is another

.exists?
.empty?
.blank?
.nil?

See more often