Hi there DEV’s Myself Jozef Clifford Behr, I need to present you 10 good Ruby options that you could be know or not. Anyway, it’s a fast learn and it’s all the time attention-grabbing to be taught new stuff, proper?!
1. Create a hash from an inventory of values
You may create a hash from an inventory of values by utilizing Hash[…]. It can create a hash like under:
Hash['key1', 'value1', 'key2', 'value2']
# => {"key1"=>"value1", "key2"=>"value2"}
2. Lambda Literal ->
Launched fairly not too long ago and the brand new manner really useful to outline scopes in Rails, the -> signal, a.okay.a Lambda Literal, lets you create lambda simply.
a = -> { 1 + 1 }
a.name
# => 2
a = -> (v) { v + 1 }
a.name(2)
# => 3
3. Double star ()**
The double star is a neat little trick in Ruby. See the next technique:
def my_method(a, *b, **c)
return a, b, c
finish
a is a daily parameter. *b will take all of the parameters handed after the primary one and put them in an array. **c will take any parameter given within the format key: worth on the finish of the strategy name.
See the next examples:
One parameter
my_method(1)
# => [1, [], {}]
A couple of parameter
my_method(1, 2, 3, 4)
# => [1, [2, 3, 4], {}]
A couple of parameter + hash-style parameters
my_method(1, 2, 3, 4, a: 1, b: 2)
# => [1, [2, 3, 4], {:a=>1, :b=>2}]
4. Deal with single object and array in the identical manner
Typically you may need to give the choice to both settle for a single object or an array of objects. As a substitute of checking for the kind of object you’ve acquired, you would use [*something] or Array(one thing).
Let’s assign two variables. The primary one is a single digit and the second is an array of digits.
stuff = 1
stuff_arr = [1, 2, 3]
Within the following instance, I exploit [*…] to loop via no matter is given.
[*stuff].every s
[*stuff_arr].every s
Identical on this one however utilizing Array(…).
Array(stuff).every s
Array(stuff_arr).every s
5. Double Pipe Equals ||=
The Double Pipe Equals is a good device to put in writing concise code.
It’s truly equal to the next:
a || a = b # Appropriate
And never this one, as lots of people assume:
a = a || b # Incorrect
The second doesn’t make sense as a result of there is no such thing as a level reassigning a if we have already got it!
This operator can be utilized to create strategies like this in your lessons. I really like to make use of it for calculations.
def whole
@whole ||= (1..100000000).to_a.inject(:+)
finish
Now you would produce other technique calling whole to get the overall worth however it is going to solely be calculated the primary time.
6. Obligatory hash parameters
This one was launched in Ruby 2.0. As a substitute of simply defining a technique that takes a hash in parameters like this:
def my_method({})
finish
You may specify the keys that you’re ready for and even outline default values for them! a and b are necessary keys.
def my_method(a:, b:, c: 'default')
return a, b, c
finish
We will attempt to name it with out giving a price for b however it received’t work.
my_method(a: 1)
# => ArgumentError: lacking key phrase: b
Since c has a default worth, we will simply name the strategy with a and b.
my_method(a: 1, b: 2)
# => [1, 2, "default"]
Or with all of them.
my_method(a: 1, b: 2, c: 3)
# => [1, 2, 3]
All we’re doing is passing a hash and utilizing some visible shortcuts however clearly, you can too cross a hash like this:
hash = { a: 1, b: 2, c: 3 }
my_method(hash)
# => [1, 2, 3]
7. Generate array of alphabet or numbers
You may need to generate an inventory of numbers or put the whole alphabet inside an array. Effectively, you should utilize ruby ranges to do that.
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. Faucet
Faucet is a pleasant little technique that improves code readability. Let’s take the next class for instance.
class Person
attr_accessor :a, :b, :c
finish
Now let’s say you need to instantiate a brand new consumer and assign a price to every of its attributes. You possibly can do it like this:
def my_method
o = Person.new
o.a = 1
o.b = 2
o.c = 3
o
finish
Or you would use faucet to do it like this.
def my_method
Person.new.faucet do |o|
o.a = 1
o.b = 2
o.c = 3
finish
finish
Principally, the faucet technique yields the calling object to the block and returns it.
9. Default worth for hash (Dangerous trick)
By default, when attempting to entry a price not outlined in a hash, you’ll obtain nil. You may truly change this at initialization.
EDIT: Don’t do that except you recognize what you’re doing. Checkout the feedback under for a whole rationalization.
On this first instance, we outline the default worth to be 0 so when a[:a] is known as, we’re getting 0 again and never nil.
a = Hash.new(0)
a[:a]
# => 0
We will cross something to the Hash initializer. Let’s attempt with a hash!
a = Hash.new({})
a[:a]
# => {}
Or a bizarre string:
a = Hash.new('lolcat')
a[:a]
# => "lolcat"
10. heredocs
I personally dislike seeing heredocs that break the code move and indentation. Since EOT takes under consideration the main areas, you often have to stay the content material to the left like this:
def my_method
<<-EOT
Some
Very
Fascinating
Stuff
EOT
finish
However there’s a trick to keep away from that. By utilizing the gsub technique with a brief regex, you possibly can mechanically take away the main areas which lets you hold your indentation constant.
def my_method
<<-EOT.gsub(/^s+/, '')
Some
Very
Fascinating
Stuff
EOT
finish
I hope you loved these little tips and I’m certain you already knew some, if not all, of them. Let me know you probably have different Ruby tips that must be added to this listing!