Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Surprising each_with_object behavior
1.9.3p194 :001 > %w(a b c).each_with_object(['foo']) { nil }
=> ["foo"]
1.9.3p194 :002 > %w(a b c).each_with_object(['foo']) { break }
=> nil
@hannahwhy

This comment has been minimized.

Copy link

@hannahwhy hannahwhy commented Mar 6, 2013

1.9.3p327 :007 > puts RubyVM::InstructionSequence.new(%q{%w(a b c).each_with_object(['foo']) { break }}).disassemble
== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
== catch table
| catch type: break  st: 0002 ed: 0020 sp: 0000 cont: 0020
|------------------------------------------------------------------------
0000 trace            1                                               (   1)
0002 putstring        "a"
0004 putstring        "b"
0006 putstring        "c"
0008 newarray         3
0010 putstring        "foo"
0012 newarray         1
0014 send             :each_with_object, 1, block in <compiled>, 0, <ic:0>
0020 leave            
== disasm: <RubyVM::InstructionSequence:block in <compiled>@<compiled>>=
== catch table
| catch type: redo   st: 0000 ed: 0005 sp: 0000 cont: 0000
| catch type: next   st: 0000 ed: 0005 sp: 0000 cont: 0005
|------------------------------------------------------------------------
0000 trace            1                                               (   1)
0002 putnil           
0003 throw            2
0005 leave            
 => nil 
@hannahwhy

This comment has been minimized.

Copy link

@hannahwhy hannahwhy commented Mar 6, 2013

(Just a note for anyone looking at the above comment: you're missing out on a lot of IM context)

@ordinaryzelig

This comment has been minimized.

Copy link

@ordinaryzelig ordinaryzelig commented Oct 15, 2014

In case anybody like me is looking for a solution to break and still return the object mid-iteration. This works:

%w(a b c).each_with_object(['foo']) { |letter, array| break array }
#=> ['foo']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment