Dealing properly with scope; came from:combine array(string) tostring?

T

Todd Benson

In much of my code, I've built an Array object before a block for
scope reasons. Is this common practice?

b = %w|a b c d e|
a = [] #instantiation
b.each {|i| a << i*2}
puts a

Todd
 
D

Daniel Finnie

You can usually use inject or collect to eliminate the a = [] line.
For example:

b = %w[a b c d e]
a = b.collect {|i| i * 2 }

Also, I would caution against using the variable i as anything but a
loop counter.

Regards,
Dan
 
T

Todd Benson

You can usually use inject or collect to eliminate the a = [] line.
For example:


b = %w[a b c d e]
a = b.collect {|i| i * 2 }

Unless you have a method that doesn't return an array (i.e. something
other than map/collect). Sometimes you have to build the array inside
the iterator. I was just wondering if this was common practice.
Also, I would caution against using the variable i as anything but a
loop counter.

For production code, I agree. But, I think even then, I wouldn't use "i".

Todd
 
R

Robert Klemme

You can usually use inject or collect to eliminate the a = [] line.
For example:

b = %w[a b c d e]
a = b.collect {|i| i * 2 }

Unless you have a method that doesn't return an array (i.e. something
other than map/collect). Sometimes you have to build the array inside
the iterator. I was just wondering if this was common practice.

Yes, that's perfectly ok. Often you can also use a variant using
#inject, like

irb(main):003:0> b = %w[a b c d e]
=> ["a", "b", "c", "d", "e"]
irb(main):004:0> b.inject([]){|ar,el| ar << el*2}
=> ["aa", "bb", "cc", "dd", "ee"]

But that would be silly in this case since there is #map / #collect.

Kind regards

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

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top