views:

75

answers:

4

@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 ?

+1  A: 

You should either do this:

@result << y

or this:

@result += [y]

The + operator expects two arrays, the << operator appends an object onto an array.

Alex Reisner
It should be the first one if you want to mutate the array. `+=` will create a new array with `y` at the end and set the `@result` variable to that new array.
Chuck
when i tried first one. It says You have a nil object when you didn't expect it!You might have expected an instance of Array.The error occurred while evaluating nil.<<
SergeiKa
@result doesn't look like an array to me - read the question
Omar Qureshi
+1  A: 

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
Omar Qureshi
This is what I would think he meant too.
Derek P.
It works too. Thanks.
SergeiKa
+2  A: 

You need to initialize @result first.

@result = []
for x in @xs
  y = x...
  @result << y
end
mckeed
@result = Array.new That was the problem. Thanks. Also other answers worked too.
SergeiKa
+1  A: 

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.

Alex Reisner