While Ruby is a regular programming language, here's how we can use a few good ideas from Functional Programming to write code in a style which is similar to the Functional Paradigm. FiltersRuby brings to us find_all and select keywords to help us use filters. In the example below we apply a filter ( which selects only even numbers, i.e. those divisible by 2) and applies it to the list of first ten natural numbers (which are given by (1..10) in Ruby ) (1..10).select{|x| x%2==0} => [2, 4, 6, 8, 10] The each keyword is a more "functional" way of doing things as opposed to regular loops. Imperative style for loop in Ruby : for counter in 1..10 puts counter end Output: 1 2 .. .. 10 Way to do it using "each" : (1..10).each{|x| puts x} 1 2 3 4 5 6 7 8 9 10 => 1..10 Iterating Through a Hash Map : {"robin"=>"red","hood"=>"green"}.each{|key,value| puts key + ":" + value} Output: {"robin"=>"red","hood"=>"green"}.each{|key,value| puts key + ":" + value} Some Examples of Recursive FunctionsComputing the Factorial of a number : def factorial(n) | ![]() Introduction to Ruby and some playing around with the Interactive Ruby Shell (irb) Introduction to Ruby - Conditional statements and Modifiers: If-then, Unless, Case Introduction to Ruby Comments - Single and Multi-Line comments Introduction to Ruby Loops - Using While, Until, For, Break, Next , Redo, Retry Introduction to Ruby - Arrays - Sorting, Filtering (Select), Transforming, Multi-Dimensional Arrays Introduction to Ruby - Strings Introduction to Ruby - Making a Script Executable Introduction to Ruby - Regular Expressions, Match, Scan Introduction to Ruby - Computing Factorials Recursively : An Example of Recursion Introduction to Ruby - Binomial Coefficients (nCr) : An Example of Recursion Introduction to Ruby - Computing a Power Set : An Example of Recursion Introduction to Ruby - Towers of Hanoi : An Example of Recursion Introduction to Ruby - Strings: Substitution, Encoding, Built-In Methods Basic Data Structures in Ruby - Insertion Sort Basic Data Structures in Ruby - Selection Sort Basic Data Structures in Ruby - Merge Sort Basic Data Structures in Ruby - Quick Sort Functional Programming with Ruby Basic Data Structures in Ruby - Stack Basic Data Structures in Ruby - The Queue Basic Data Structures in Ruby - Linked List - ( A Simple, Singly Linked List) |
Computer Science >