开发者

Inserting new item to instance variable in Ruby on Rails

开发者 https://www.devze.com 2022-12-14 01:12 出处:网络
@xs stores urls like www.yahoo.com, www.google.com for x 开发者_C百科in @xs y = x... #do something with x

@xs stores urls like www.yahoo.com, www.google.com

for x 开发者_C百科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 ?


You need to initialize @result first.

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


You should either do this:

@result << y

or this:

@result += [y]

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消