Reputation: 3
@xs stores urls like www.yahoo.com, www.google.com
for x in @xs
y = x... #do something with x
@result += y #i want to do something like that. i want to store them in @result. What do i have to write in here?
end
Sorry for noob question. By the way how do you call @result ? Is it an instance variable or an array ?
Upvotes: 0
Views: 1344
Reputation: 29447
If you want to take every element in an array and change it, the idiomatic Ruby way is to use map or collect:
@new_urls = @urls.map do |url|
# change url to its new value here
end
You don't need to manually assign it to @new_urls, just write a statement that returns the desired value, like url.upcase
or whatever you want to do.
Upvotes: 1
Reputation: 9828
You need to initialize @result
first.
@result = []
for x in @xs
y = x...
@result << y
end
Upvotes: 3
Reputation: 9093
From what I can make out from the question, you want to mutate the contents of the already existing array
@mutated_xs = @xs.collect do |x|
y = x.do_something # some code for to do something to x returning y
x += y # mutate existing x here
end
puts @mutated_xs.inspect
Upvotes: 1
Reputation: 29447
You should either do this:
@result << y
or this:
@result += [y]
The +
operator expects two arrays, the <<
operator appends an object onto an array.
Upvotes: 1