Ruby Expressions | Best Practices
Writing ruby expressions in a good/optimized way doesn't only increases the efficiency of the code but also increases the code readability. Here are some good way to write ruby expressions.1. Use of unless
If we are checking an if condition that do not have else part than we should use unless.
example:
# Bad code if ! names.empty? puts names end # Good code unless names.empty? puts names end
2. Nil condition
If anything that returns nil. So instead of checking for nil we can directly use if condition on it, as ruby considers nil as false.
example:
# Bad code if attachment.file_path != nil puts "we have a path" end # Good code if attachment.file_path puts "we have a path" end
3. Not everything evaluates to false
For example "" is treated as true, 0 is treated as true, [] empty array is treated as true.
example:
# Bad code unless name.length puts"name is required" end
Here name.length is never going to be false as 0 would be considered as true. So we need to be careful about this.
4. Inline conditionals
Inline conditional should be used for better readability.
example:
# Bad code if password.length < 8 puts "short password" end unless username puts "username not set" end # Good code puts "short password" if password.length <8 puts "username not set" unless username
6. Using short-circuit assignment
We can use || operator for short-circuit assignment. In the example below if the first assignment before || is nil than only it will go for the other part. For example in first one, the nil is encountered and than it checks for the other one i.e. 1, it assigns 1 to result. In second one, as soon as it gets 1, it doesn't check of nil. In the third one, as soon as it gets 1, it doesn't check for 2 and assigns 1 to result.
result = nil || 1 # output 1 result = 1 || nil # output 1 result = 1 || 2 # output 1
If the first part of the expression is evaluated to true than second part is not even going to get touched.
example: check of the names, if there are no names than set the names to an empty array
# Bad code names = Users.names names = [] unless names # Good code names = User.names || []
0 comments:
Post a Comment