menu

Search By Label

Syntactic sugar refers to the little bit of ✨ magic ✨ Ruby provides you in writing easier to read and more concise code. In Ruby this means leaving out certain symbols, and spaces or writing some expression with a helper of some kind one of these possibilities is the sandwich method, we look more at it here: 

It is common when we begin to handle an array in a each to do it specific actions thing like that:
array = [1, 2, 3, 4]
new_array = []
array.each do |element|
  new_array << element * 2
end
new_array
# => [2, 4, 6, 8]

Today I learned how simplified it is to handle this type of interaction by thinking about this magic we talked about before. the first thing that is important here is to remember that the use of each handle and return the same array and for this reason, it is necessary to create a new_array variable to inject the new values of the product to element * 2

Most of the time, if you have to use the sandwich method, there is probably a higher-level iterator that you could use that will allow you to perform the function on the array or hash without using the sandwich method. In this case, your best bet would be map :

array = [1, 2, 3, 4]
array.map do |element|
  element * 2
end
# => [2, 4, 6, 8]


We can use the following method to ensure a variable value is between a specific range

# Ensure between 1 and 100
111.clamp(1, 100)
# => 100
-1.clamp(1, 100)
We can use the following methods to ensure a variable is always min or max value:

# Ensure the value is one or more
[value, 1].min

# Ensure the value is 100 or less
[value, 100].max
Recently, I became interested in Rails' Action Mailbox, and I read several articles including the official documentation. One article from Prograils (https://prograils.com/real-life-examples-adding-action-mailbox-to-a-rails-6-app) particularly caught my attention due to its discussion on using the simple_command gem (https://github.com/nebulab/simple_command). This article shows how the gem can help you avoid repeating the way you invoke your services or classes. It allows you to structure classes like this:

# define a command class
class AuthenticateUser
  prepend SimpleCommand

  # optional, initialize the command with some arguments
  def initialize(email, password)
    @email = email
    @password = password
  end

  # mandatory: define a #call method. its return value will be available
  #            through #result
  def call
    if user = User.find_by(email: @email)&.authenticate(@password)
    ...
end

So you can invoke it like this
AuthenticateUser.call(session_params[:email], session_params[:password])

And I wondered how the SimpleCommand module might be structured. Additionally, I considered how it could support keyword arguments in the form of:
def my_method(value:, second_value:)
  puts "value #{value}, second_value #{second_value}"
end
my_method(value: 'value one', second_value: 'value two')

In fact, it is quite simple. Let’s define it in two different ways without using any additional dependencies:

Using class_eval and self for defining a class method

module SimpleCommand
  def self.included(klass)
    klass.class_eval do 
      def self.call(*args, **kwargs)
        puts "args #{args}"
        new(*args, **kwargs).call
      end
    end
  end
end

or

Using extend to define the methods as class methods

module SimpleCommand
  def self.included(klass)
    klass.extend(ClassMethods)
  end
  
  module ClassMethods
    def call(*args, **kwargs)
      new(*args, **kwargs).call
    end
  end
end

And here is how you can use it after that
class NamedArguments
  include SimpleCommand
  def initialize(value: , second:)
    @value = value
    @second = second
  end

  def call
    puts "the method in myClass @value: #{@value}, @second #{@second}"
  end
end

NamedArguments.call(value: 'the value', second: 'from second')

Or using positional arguments

class SimpleArguments
  include SimpleCommand
  def initialize(valueOne, valueTwo)
    @valueOne = valueOne
    @valueTwo = valueTwo
  end

  def call
    puts "the method in myClass @value: #{@valueOne}, @second #{@valueTwo}"
  end
end

SimpleArguments.call('arg one', 'arg two')

There you have it!

lambda = lambda {|value| value ** value }

lambda.(10)
lambda.call(10)
lambda === 10
lambda[10]

proc = Proc.new {|value| value ** value }

proc.(10)
proc.call(10)
proc === 10
proc[10]

You can use a break

(1..10).to_a.each.with_index do |element, index|
  puts "element #{element}, index: #{index}"
  break if index == 3
end

Using catch and throw

Following a syntax like this

catch :label do
  (1..10).to_a.each.with_index do |e, index|
    throw :label if condition
  end
end

Practical example

def my_method
  result = []
  catch :completed do
    (1..10).to_a.each.with_index do |element, index|
      result << element
      throw :completed if index == 3
    end
  end
  result
end
my_method
=> [1, 2, 3, 4]

Using Return

If you want to use return, it will stop the iterations but also the method itself, so be aware of that, and that remember that the return clause only works if it is contained in a method

def return_example
  values = []
  (1..10).to_a.each_with_index do |element, index|
    values << element
    return values if index == 3
  end
end

return_example
=> [1, 2, 3, 4]
To get a value and the index of this element into an array is useful this method, for example:

[11,22,31,224,44].each_with_index { |val,index| puts "index: #{index} for #{val}" if val < 30}
  index: 0 for 11
  index: 1 for 22
  => [11, 22, 31, 224, 44]

" Hello world ".strip # => "Hello world"
In Ruby, the .is_a? method is used to check if an object is an instance of a particular class or a subclass of that class. It allows you to determine if an object belongs to a certain class in the class hierarchy. The .is_a? method returns true if the object is an instance of the specified class or one of its subclasses, and false otherwise. 

Example:

# Define a class 
class Animal 
end# Create an object 
dog = Animal.new# Check if the object is an instance of a class 
puts dog.is_a?(Animal) # true 
puts dog.is_a?(Object) # true, since all objects are instances of Object 
puts dog.is_a?(String) # false, since a dog is not a String
This method is used to replace the first occurrence of a specified pattern. 

Example:

text = "Hello, World! This is a test. Hello, Universe!" 
new_text =text.sub("Hello", "Hi") 
puts new_text # => "Hi, World! This is a test. Hello, Universe!" 

This method is used to retrieve a list of all the public methods available for an object. This method returns an array of symbols, where each symbol represents a method that can be called on the object.

This method can be used to know the class of an object, which allows you to inspect and work with the class itself, rather than just the object. 

Example:

"Hello".class # => String 
10.class # => Number 
10.0.class # => Float 

This method is the opposite of the .blank? method. It is used to check whether a string, array, or other data structure contains meaningful content, and it returns true if the object is not empty, contains non-whitespace characters, or is not nil. Otherwise, it returns false.

Example:

"".present? # false (empty string) 
" ".present? # false (whitespace characters only) 
nil.present? # false (nil) 
"hello".present? # true (contains non-whitespace characters) 
[1, 2, 3].present? # true (array with elements) 

This method is used to check whether a string, array, or other data structure is empty or contains only whitespace characters.
 It returns true if the object is empty contains only whitespace, or is nil. Otherwise, it returns false. 

Example:

"".blank? # true (empty string) 
" ".blank? # true (whitespace characters only) 
nil.blank? # true (nil) 
"hello".blank? # false (contains non-whitespace characters) 
[1, 2, 3].blank? # false (array with elements)

Ruby's Enumerable#cycle offers an easy way to either repeat a certain pattern n times or just to switch between two predefined states. 

Repeating a certain pattern:

irb> array = [1, 2, 3]  
=> [1, 2, 3] 
irb> array.cycle(3).to_a  
=> [1, 2, 3, 1, 2, 3, 1, 2, 3] 

Switching between two states:

irb> button = ['on', 'off'].cycle  
=> # 
irb> button.next  
=> "on" 
irb> button.next  
=> "off"