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

Discussion in 'Ruby' started by Todd Benson, Mar 20, 2008.

  1. Todd Benson

    Todd Benson Guest

    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 Benson, Mar 20, 2008
    1. Advertisements

  2. 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.

    Daniel Finnie, Mar 20, 2008
    1. Advertisements

  3. Todd Benson

    Todd Benson Guest

    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.
    For production code, I agree. But, I think even then, I wouldn't use "i".

    Todd Benson, Mar 21, 2008
  4. 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 Klemme, Mar 21, 2008
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.