Skip to content

Instantly share code, notes, and snippets.

@pokk
Created July 3, 2017 06:23
Show Gist options
  • Select an option

  • Save pokk/5d8abb33eb9a86ea8e7a907e2a44bcf0 to your computer and use it in GitHub Desktop.

Select an option

Save pokk/5d8abb33eb9a86ea8e7a907e2a44bcf0 to your computer and use it in GitHub Desktop.
a Block, a Proc, a Lambda, and map class shorthand

[TOC]

Interduction

Using block, proc, lambda or shorthand for devleoping easily. We don't need to code so many words and coding style is elegant.

Map class shorthand

We're often using the simplest way to code a map lambda method. A well-known example:

list = [2, 3, 4, 6, 1, 2, 3, 5]

list.map { |num| num + 3 }
# output >> [5, 6, 7, 9, 4, 5, 6, 8]

using proc for reducing redundant code

If we're using the same block or lambda method. We're able to use kind of local variable instead.

function = proc { |num| num + 3 }

list = [2, 3, 4, 6, 1, 2, 3, 5]

list.map(&function)
# output >> [5, 6, 7, 9, 4, 5, 6, 8]

call by other class method

Sometimes you may call the method you made as like XXCLASS.xxmethod(xxVAR1, xxVAR2) or object method. In this situation you could code as like below.

class Calculation
  def self.add_five_times(num)
    num * 5
  end
end

list = [2, 3, 4, 6, 1, 2, 3, 5]

# Call a static method(Class Method).
list.map(&Calculation.method(:add_five_times))
# output >> [10, 15, 20, 30, 5, 10, 15, 25]

call by object class method

Or a method in the same class you'd like to use in your map method.

def add_five_times(num)
  num * 5
end

list = [2, 3, 4, 6, 1, 2, 3, 5]

# Call an object method or local method. 
list.map(&method(:add_five_times))
# output >> [10, 15, 20, 30, 5, 10, 15, 25]

call from the element of list

list = [2, 3, 4, 6, 1, 2, 3, 5]

# Call an object method or local method. 
list.map(&:to_s)
# output >> ["2", "3", "4", "6", "1", "2", "3", "5"]

Issue

This is a big issue what I wanna know there is a good way for putting a element's method as parameter.

  • Using &method(:add_five_times) with the elements' method as parameters.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment