Skip to content

Instantly share code, notes, and snippets.

@kachick
Forked from aflc/file0.rb
Created November 23, 2012 14:45
Show Gist options
  • Save kachick/4135941 to your computer and use it in GitHub Desktop.
Save kachick/4135941 to your computer and use it in GitHub Desktop.
Ruby1.9のブロックについて勉強した ref: http://qiita.com/items/413f710b126a869cb797
(1..3).map {|x|x * 2} # => [2, 4, 6]
a = (1..3).to_enum
a.next # => 1
def f1(x)
x * 2
end
(1..3).map {|x|f1(x)} # => [2, 4, 6]
f1 = lambda {|x| x * 2} # f1とf2は同じ意味。f1とf3はスコープの考えがちょっと違う(割愛)
f2 = ->(x) {x * 2}
f3 = Proc.new {|x|x * 2}
(1..3).map(&f1) # => [2, 4, 6]
(1..3).map(&f2) # => [2, 4, 6]
(1..3).map(&f3) # => [2, 4, 6]
def itr_func
(1..3).each {|x|yield x}
end
l = []
itr_func {|x|l << x}
l # => [1, 2, 3]
# (1..3).to_a ?
enum = Enumerator.new do |yielder|
yielder.yield 1
yielder.yield 2
yielder.yield 3
end
enum.next # => 1
enum.next # => 2
enum.next # => 3
enum = (1..3).each
enum.next # => 1
enum.next # => 2
enum = ->(x){x * 2}
(1..3).map(&enum).map(&enum) # => [4, 8, 12]
enum = Enumerator.new do |yielder|
yielder.yield 1
yielder.yield 2
yielder.yield 3
end
proder = ->(x) {x * 2}
enum.lazy.map(&proder).map(&proder).to_a # => [4, 8, 12]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment