Skip to content

Instantly share code, notes, and snippets.

@serdardalgic
Created October 15, 2014 08:54
Show Gist options
  • Save serdardalgic/e19394b2c0ee2fd8427a to your computer and use it in GitHub Desktop.
Save serdardalgic/e19394b2c0ee2fd8427a to your computer and use it in GitHub Desktop.
Ruby block_given and yield example
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
@serdardalgic
Copy link
Author

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

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