📜 ⬆️ ⬇️

Several useful ruby ​​tricks that (possibly) will improve your code.

Bored during this rainy holiday weather, I came across an entertaining little article on the blog with the talking title Samurails, which describes some interesting ruby ​​tricks that will surely be interesting to beginners.

So let's get started.

Create a hash from an array


Easy peasy. Put the Hash command in front of any array and get ready key / value pairs:
')
Hash['key1', 'value1', 'key2', 'value2'] # => {"key1"=>"value1", "key2"=>"value2"} 


Lambda as ->


The opportunity to put down lambda with the help of -> appeared relatively recently, we will try:

 a = -> { 1 + 1 } a.call # => 2 a = -> (v) { v + 1 } a.call(2) # => 3 

Double asterisk (**)


How do you like this method:

 def my_method(a, *b, **c) return a, b, c end 

a is a common argument. * b will take all arguments after “a” and output them in an array, but ** c only accepts parameters in key / value format, after which it will give us a hash. See examples:

One argument:

 my_method(1) # => [1, [], {}] 

Argument set:

 my_method(1, 2, 3, 4) # => [1, [2, 3, 4], {}] 

Argument set + key / value pairs

 my_method(1, 2, 3, 4, a: 1, b: 2) # => [1, [2, 3, 4], {:a=>1, :b=>2}] 

In my opinion, cool.

We handle a variable and an array in the same way.


Sometimes ( only sometimes ) you may want to run a method on an object without checking its type. I mean, handle an array in the same way as, say, a regular variable. In such cases, you can go two ways - use [* something] or Array (something).

Let's try. Assign two variables: a number and an array of numbers

 stuff = 1 stuff_arr = [1, 2, 3] 

Using [*] we can equally successfully iterate over both variables:

 [*stuff].each { |s| s } [*stuff_arr].each { |s| s } 

Identically:

 Array(stuff).each { |s| s } Array(stuff_arr).each { |s| s } 


|| =



An excellent key to reducing the number of lines of our code is to use || =

It is important to understand that this statement works like this:

 a || a = b #  


Not so:

 a = a || b # ! 


This operator is perfect for performing mathematical operations:

 def total @total ||= (1..100000000).to_a.inject(:+) end 


Now we can use total in other methods, but it will be counted only once, which will affect the performance of our application.

Required Hash Parameters



A completely new feature of the second rubie. Instead of defining a method with a hash as the argument to be taken:

 def my_method({}) end 

Now we can clearly identify the keys that we are waiting at the entrance. Moreover, we can determine their values!

In this example, a and b are mandatory keys:

 def my_method(a:, b:, c: 'default') return a, b, c end 

We can try to send only “a” to the method and run into an error:

 my_method(a: 1) # => ArgumentError: missing keyword: b 

Since we specified the default value for "c", we only need to provide the method with the keys "a" and "b":

 my_method(a: 1, b: 2) # => [1, 2, "default"] 

Or we can send all three:

 my_method(a: 1, b: 2, c: 3) # => [1, 2, 3] 

We can be more concise:

 hash = { a: 1, b: 2, c: 3 } my_method(hash) # => [1, 2, 3] 

Generate an alphabet or chain of numbers using range


The trick is quite old, but suddenly someone does not know.

 ('a'..'z').to_a # => ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] (1..10).to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

Tap


Tap is an excellent method that can improve the readability of our code. Suppose we have a class:

 class User attr_accessor :a, :b, :c end 

Now, let's say we wanted to create a new user, with attributes. You can do it like this:

 def my_method o = User.new oa = 1 ob = 2 oc = 3 o end 

And you can use tap:

 def my_method User.new.tap do |o| oa = 1 ob = 2 oc = 3 end end 

Source: https://habr.com/ru/post/257151/


All Articles