Skip to content

Instantly share code, notes, and snippets.

@tokhi
Last active April 1, 2016 12:13
Show Gist options
  • Save tokhi/9d9ae67fbe21f9154dd1 to your computer and use it in GitHub Desktop.
Save tokhi/9d9ae67fbe21f9154dd1 to your computer and use it in GitHub Desktop.
Some cool ruby tips and tricks...

Some nice ruby tips and trikcs

Enumerable modules in ruby

Finding positive numbers in an array:

# instead of using sort of a for loop, but we can express the same login using a simple select statement:
2.3.0 :001 > [1,-12,3,-4,-10,2].select {|n| n.positive? }
 => [1, 3, 2]
2.3.0 :002 > # even more shorter
2.3.0 :003 >   [1,-12,3,-4,-10,2].select(&:positive?)
 => [1, 3, 2]

There are generally two ways to call an Enumerable method:

By passing a block like we’ve seen above
By passing a symbol with an & character before it, otherwise known as Symbol#to_proc

In below snippet map method will iterate over some piece of data e.g; an array

names = User.limit(3).map { |user| user.name }
# => ["name1", "name2", "name3"]
Here’s another method that’s included in the `Enumerable` module: `reduce`. In this case:

["First", "Middle", "Last"].reduce { |str, val| "#{str}, #{val}" }
# => "First, Middle, Last"

Make something Enumerable

Now that we’ve taken a look at how to use the methods found within Enumerable

class Array
  include MyEnumerable
end
module MyEnumerable
  def my_reduce(acc, operator = nil, &block)
    raise ArgumentError, 'both operator and actual block given' if operator && block
    raise ArgumentError, 'either operator or block must be given' unless operator || block

    # if no block, create a lambda from the operator (symbol)
    block = block || -> (acc, value) { acc.send(operator, value) }

    each do |value|
      acc = block.call(acc, value)
    end
    acc
  end
end

p [1,2,3,4].my_reduce(0) { |total, num| total + num }
# => 10
p [1,2,3,4].my_reduce(0, :+)
# => 10

reference: blog.codeship.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment