Skip to content

Instantly share code, notes, and snippets.

@daniel-g
Created January 27, 2011 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniel-g/798293 to your computer and use it in GitHub Desktop.
Save daniel-g/798293 to your computer and use it in GitHub Desktop.
Blocks
def fibonacci_up_to(number)
i1, i2 = 1, 1
while i1 <= number
yield i1
i1, i2 = i2, i1+i2
end
end
fibonacci_up_to(40){|fib| puts fib}
def triangle_up_to(number)
i, k = 1, 1
while i <= number
yield i
k += 1
i += k
end
end
triangle_up_to(100){|tr| puts tr}
require "mathn"
Prime.new.each{|p| puts p; break if p > 100}
def word_counter(word)
words_array = word.scan /[\w'^"]+/
words_hash = Hash.new(0)
words_array.each do |word|
words_hash[word] += 1
end
words_hash.each{|word, count| yield word, count}
end
word_counter("a a a a b b b"){|word, counter| puts "The word '#{word}' appears #{counter} times"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment