2009-12-16 60 views
0

@xs商店的网址一样www.yahoo.com,www.google.comon Rails的插入到Ruby的实例变量新项目

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 

对不起,noob问题。顺便说一句,你怎么称呼@result?它是一个实例变量还是数组?

+0

@result将被每次迭代覆盖 - 我不认为这就是你想如何去做 – 2009-12-16 22:14:59

回答

3

需要初始化@result第一的内容。

@result = [] 
for x in @xs 
    y = x... 
    @result << y 
end 
+0

@result = Array.new这是问题所在。谢谢。其他答案也起作用。 – SergeiKa 2009-12-16 22:30:04

1

您应该这样做:

@result << y 

或该:

@result += [y] 

+操作者需要两个阵列中,操作者<<追加对象到阵列。

+0

它应该是第一个,如果你想改变数组。 '+ ='将在最后创建一个带有'y'的新数组,并将'@ result'变量设置为该新数组。 – Chuck 2009-12-16 22:08:00

+0

当我第一次尝试。它说 当你没有想到它时,你有一个零对象! 您可能预期了Array的一个实例。 评估nil时出现错误<< – SergeiKa 2009-12-16 22:11:06

+0

@result对我来说看起来不像一个数组 - 看到这个问题 – 2009-12-16 22:11:25

1

从我可以从问题中做出来,要变异已有的阵列

@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 
+0

这就是我认为他的意思。 – 2009-12-16 22:24:22

+0

它也可以工作。谢谢。 – SergeiKa 2009-12-16 22:32:53

1

如果你想抓住每个数组中的元素并改变它,惯用的Ruby的方法是使用地图或收集:

@new_urls = @urls.map do |url| 
    # change url to its new value here 
end 

你并不需要手动将其分配给@ new_urls,只需编写一个返回所需值的语句,如url.upcase或任何你想做的事情。