| Start |
|---|
| Blocks and Procs and Lambdas |
| Partial Application and Currying Technically, Ruby doesn't have functions, but methods. However, a Ruby method behaves almost identically to functions in other language: This normal method/function takes a parameter Instead of returning a number, If you want to actually get the tripled number, you need to call (or "reduce") the lambda: Or more concisely: Currying and Partial ApplicationsThis is not useful in terms of defining very basic functionality, but it is useful if you want to have methods/functions that are not instantly called or reduced. For example, let's say you want to define methods that add a number by a specific number (for example However, you could also do this: Using lambda calculus we can say that More useful examples of curryingLet's say we have really big general formula, that if we specify certain arguments to it, we can get specific formulae from it. Consider this formula: This formula is made for working in three dimensions, but let's say we only want this formula with regards to y and z. Let's also say that to ignore x, we want to set it's value to pi/2. Let's first make the general formula: Now, let's use currying to get our Then to call the lambda stored in This is pretty simple, but let's say we want to get the formula for In this case, we need to provide placeholders for the parameter we aren't pre-filling. For consistency we could write Here's how the lambda calculus works for Now let's look at For more reading about lambda calculus try this (opens new window). |
| Objects as block arguments to methods Putting a This is a common pattern in Ruby and many standard classes provide it. For example, This enables the useful |
| Converting to Proc Objects that respond to The class Symbol defines Method objects also define |
| Blocks Blocks are chunks of code enclosed between braces Note: braces have higher precedence than YieldingBlocks can be used inside methods and functions using the word Be careful though if
While this is a simple example As you can see using VariablesVariables for blocks are local to the block (similar to the variables of functions), they die when the block is executed. Blocks can't be saved, they die once executed. In order to save blocks you need to use |
| Converting to Proc Objects that respond to The class Symbol defines Method objects also define |
Read Article
https://develop.horje.com/learn/1434/reference