Troubles with blocks

Hi,

I am a Python programmer and I’ve just started learning Ruby. Until now,
I’ve enjoyed it, but I am having troubles with some methods that require
blocks.

This is a simple example that (I expect) summarizes my problems - how to
obtain a list of pairs [index, value] (or [value, index], it doesn’t
matter) from an array:

Python:

list(enumerate([‘a’,‘b’,‘c’]))
=> [(0, ‘a’), (1, ‘b’), (2, ‘c’)]

Ruby:

t = []; [‘a’,‘b’,‘c’].each_with_index { |*x| t << x }; t
=> [[“a”, 0], [“b”, 1], [“c”, 2]]

Which is a very ugly solution. How could I do this on Ruby without a
temporal variable?

thanks

On Jan 3, 2008 6:49 PM, Holden H. [email protected] wrote:

Python:
temporal variable?

thanks

Posted via http://www.ruby-forum.com/.

Hmm, I can’t find a shorter way than what you’ve got. Why are you trying
to
get this kind of information? Maybe there’s something earlier in your
code
that can be made more Ruby-esque to make this easier for you.

Jason

On Jan 3, 2008, at 6:49 PM, Holden H. wrote:

Ruby:

t = []; [‘a’,‘b’,‘c’].each_with_index { |*x| t << x }; t
=> [[“a”, 0], [“b”, 1], [“c”, 2]]

Which is a very ugly solution. How could I do this on Ruby without a
temporal variable?

In Ruby 1.8:

require ‘enumerator’
%w{a b c}.enum_for(:each_with_index).to_a

In Ruby 1.9:

%w{a b c}.each_with_index.to_a

Gary W.

On Fri, 4 Jan 2008 08:49:54 +0900, Holden H. [email protected]
wrote:

Which is a very ugly solution. How could I do this on Ruby without a
temporal variable?

Try this (you will need to require ‘enumerator’):

[‘a’,‘b’,‘c’].enum_with_index.to_a

-mental

On Jan 3, 2008 7:13 PM, MenTaLguY [email protected] wrote:

=> [[“a”, 0], [“b”, 1], [“c”, 2]]

Ah, that’s where enum_with_index is. I was wondering why it wasn’t
working
for me.

Jason

Gary W. wrote:

In Ruby 1.8:

require ‘enumerator’
%w{a b c}.enum_for(:each_with_index).to_a

In Ruby 1.9:

%w{a b c}.each_with_index.to_a

Thanks! that’s exactly what I was looking for. I had already tried the
last solution but I got a “no block given” error (I’m using Ruby 1.8).
I’m glad to hear that versions 1.9 and higher support this construct.