There are many tricks in Ruby that you may not know about, but are actually very useful. The following author on the combination of their own experience, to share a few.

1. Construct the Hash

You can construct a Hash from a list of values by Hash[…] Method, which will create a Hash like this:

Hash['key1', 'value1', 'key2', 'value2']
# => {"key1" => "value1", "key2" => "value"}

2.Lambda literal ->

Defining a lambda can be done using the popular -> literal also used in Rails, which makes it easy to define a lambda object

A = - > {1 + 1} a.c all # = a = > 2 - > (arg) + 1} {arg # containing ginseng a.c all (2) to pass an argument # # = > 3

3. The binary * *

Binary stars are a bit of magic in Ruby. Here’s how:

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

A is a regular argument, B will take all the arguments after the first argument and put them in an array, and c will get any key: value argument passed to the method.

Consider the following example: a parameter

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

More than one parameter

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

More than one argument + hash-style argument

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

4. Operate on individual objects and arrays in the same way

Sometimes you may give an option to accept a single object or an Array of objects first, rather than checking the type of object you receive at the end, using either [*type] or Array(type).

Let’s set two variables, the first is a single object and the second is an array of numbers:

obj = 1
obj_arr = [1, 2, 3]

In the following example, use [*…] for any given object. To cycle:

[*obj].each { |s| s } # => [1]
[*obj_arr].each { |s| s } # => [1, 2, 3]

Same effect as above, this time using Array(…) :

Array(stuff).each { |s| s } # => [1]
Array(stuff_arr).each { |s| s } # => [1, 2, 3]

5. | | = symbol operation

Using the | | = operator can write very concise code

It is actually expressed in the same way as:

A | | = b # is correct

Most people think it’s the same as the following, but it’s not:

A = a | | b # errors

Because if a already exists, the second way is to assign to a again, but that doesn’t really make sense.

6. Mandatory hash parameters

This was introduced in Ruby 2.0, where you can define methods to accept arguments of type hash, like this:

def my_method({})
end

You can specify the key that you want to accept values for, or you can specify a default value for the key. The following a and b are the keys that specify the values to accept:

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

If we call b without passing it a value, we get an error:

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

Since c has a default value, we can only pass values to A and B:

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

Or pass values to all keys:

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

What we do most of the time is pass in a hash, which just makes it more obvious, like this:

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

7. Generate characters or character arrays

You might want to generate a list of numbers or put all the characters into an array. You can use Ruby’s Range to do this.

A to Z:

('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 to 10:

(1.. 10).to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

8. Tap

Tap is a great little way to improve code readability. Let’s take the following class as an example:

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

Now to instantiate an object and assign its properties, you might do something like this:

def my_method
o = User.new
o.a = 1
o.b = 2
o.c = 3
o
end

Or you can use tap to do it in the following way:

def my_method
User.new.tap do |o|
o.a = 1
o.b = 2
o.c = 3
end
end

Basically, the TAP method brings the called object into the code block and returns it.

9.Hash default value

By default, when we try to accept a value that’s not defined in the hash, you’re going to get nil. But you can change that when you initialize it. (Hint: Don’t do this unless you know what you’re doing.)

In the first example, we defined a default value of 0, so when we get a[:a] we get 0 instead of nil:

a = Hash.new(0)
a[:a]
# => 0

We can pass any form of type into the Hash initial function:

a = Hash.new({})
a[:a]
# => {}

Or a string:

a = Hash.new('lolcat')
a[:a]
# => "lolcat"

10. Here document

One drawback of here documents is that they can affect code flow and indentation, since here indents two Spaces, but sometimes you might write each line to the left for final consistency, like this:

def my_method
<<-here ruby="" stricks="" interesting="" right="" here="" end<="" pre="">

A trick to avoid this is to add a regular expression using the gsub method. You can automatically remove the space so that you can keep the indentation.

def my_method
<<-here.gsub( ^\s+="" , '')="" ruby="" stricks="" interesting="" right="" here="" end<="" pre="">

If you feel good about this article, please support the author! Encourage the author to write better and more articles! Hey hey!