each, stuck up...

M

Mayuresh Kathe

Hello,

A while back there was this discussion about what code could crash irb

I did the following in irb 1.9;
a = [3, 2, 1, 0, -1, -2, -3]
a.each {|x| a[x] = x +1}

irb just got stuck, it wouldn't do anything for a while until I hit
Ctrl+c, doing so threw up the following messages;
IRB::Abort: abort then interrupt!!
from /usr/lib/ruby/1.9.0/irb.rb:81:in `irb_abort'
from /usr/lib/ruby/1.9.0/irb.rb:243:in `signal_handle'
from /usr/lib/ruby/1.9.0/irb.rb:66:in `block in start'
from (irb):2:in `block (4 levels) in irb_binding'
from (irb):2:in `each'
from (irb):2
from /usr/lib/ruby/1.9.0/irb.rb:150:in `block (2 levels) in eval_input'
from /usr/lib/ruby/1.9.0/irb.rb:259:in `signal_status'
from /usr/lib/ruby/1.9.0/irb.rb:147:in `block in eval_input'
from /usr/lib/ruby/1.9.0/irb.rb:146:in `eval_input'
from /usr/lib/ruby/1.9.0/irb.rb:70:in `block in start'
from /usr/lib/ruby/1.9.0/irb.rb:69:in `catch'
from /usr/lib/ruby/1.9.0/irb.rb:69:in `start'
from /usr/bin/irb1.9:13:in `<main>'

After that it wouldn't accept any more commands till I exit the
session by executing "exit".

I'm kind-a obtuse at the moment, could someone please tell me what was
it that I did wrong.
I wanted to increment the values of each element of the array.

~Mayuresh
 
J

James Coglan

[Note: parts of this message were removed to make it a legal post.]
I did the following in irb 1.9;
a = [3, 2, 1, 0, -1, -2, -3]
a.each {|x| a[x] = x +1}



I'm kind-a obtuse at the moment, could someone please tell me what was
it that I did wrong.
I wanted to increment the values of each element of the array.



In the above example, x is the value of each member of the array, not its
position. You want this instead:

a.map! { |x| x + 1 }

map! takes each member of an array and performs some transformation on it,
writing the result back to the array.
 
R

Robert Dober

Hello,

A while back there was this discussion about what code could crash irb

I did the following in irb 1.9;
a = [3, 2, 1, 0, -1, -2, -3]
a.each {|x| a[x] = x +1}
looks like an endless loop to me, well and to irb too ;)
See this
ruby -e 'a=[1];a.each{|x| a[x] = x.succ; p a}'
HTH
Robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top