Created
October 15, 2014 08:54
-
-
Save serdardalgic/e19394b2c0ee2fd8427a to your computer and use it in GitHub Desktop.
Ruby block_given and yield example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyArray | |
attr_reader :array | |
def initialize(array) | |
@array = array | |
end | |
def sum(initial_value = 0) | |
return array.inject(:+) + initial_value unless block_given? | |
sum = initial_value | |
array.each {|n| sum += yield(n) } | |
sum | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem Statement
Given a custom class MyArray,
write a 'sum' method that takes a block parameter.
Example:
my_array = MyArray.new([1, 2, 3])
my_array.sum gives 6
my_array.sum(10) gives 16
my_array.sum(0) {|n| n ** 2 } gives 14