Victor
Victor

Reputation: 13378

Modify an array and push to form another array

What is a better way than this:

X = %w(a b c)
Y = %w()
  X.each do |x|
    Y << "good_" + x
  end

Thanks.

Upvotes: 0

Views: 56

Answers (3)

user904990
user904990

Reputation:

to have them both defined on same line:

y = ( x = %w[a b c] ).map { |i| 'good_%s' % i }

y
=> ["good_a", "good_b", "good_c"]

x
=> ["a", "b", "c"]

Upvotes: 1

Rubyman
Rubyman

Reputation: 874

collect method on array will do

Y = X.collect{|e|'good_'+e} 

OR

directly

Y = %w(a b c).collect{|e|'good_'+e}

Upvotes: 3

Jake Dempsey
Jake Dempsey

Reputation: 6312

%w(a b c).map{|x| "good_#{x}"}

Upvotes: 6

Related Questions