【发布时间】:2012-06-28 20:31:26
【问题描述】:
我的问题是我无法在 Ruby 中通过引用传递。
我有两个函数searching 和get_title_ids。
我在searching 中有两个数组
(1) 标题 (2) href
需要更新。
def searching
title = []
href = []
(0..20).step(10) do |i|
prev= title.length
title, href = get_title_ids(i, title, href) ## <<-- Should have just done "get_title_ids(i, title, href)"
## something which on next iteration will increase the ids and hrefs
puts "\nthe title lenght is #{title.length} and href length is #{href.length}\n"
assert_operator prev,:<,title.length,"After scrolling to bottom no new jobs are getting added"
end
end
def get_title_ids (start_from=0, title=[], href=[])
#Part of code which can store all links and titles of jobs displayed
(start_from..(titles.length-1)).each do |i|
unless titles[i].text.chomp
title << titles[i].text.chomp
href << titles[i].attribute("href")
end
end
end
return [title, href] ### <<---- this is what messed it up
end
问题是我无法将push 新 元素放入searching 中定义的数组title 和href。
每次我打电话给get_title_ids 我都不想收集我之前收集的数据(因此是 start_form)。
我的问题不是记忆而是时间。所以我不太担心在调用get_title_ids 函数时数据被复制,而不是我不得不浪费时间来报废我在前一个 for 循环中已经报废的数据。
那么有谁知道如何在 Ruby 中通过引用破解 pass。
编辑
通过阅读以下问题,我发现我不需要从get_title_ids 执行return。然后一切都奏效了。
【问题讨论】:
-
即使一个引用类型的对象通过值传递,它仍然是引用内存中的同一个对象。
-
太棒了!这样我就可以避免内存重复:),但是我如何
push数组中的元素通过值/引用传递 -
@seleniumnewbie:看我的回答:)
-
我认为这里的问题不是因为引用,而是因为你不知道如何使用迭代器。
-
@megas,我认为迭代器很好。是
return搞砸了。感谢您的评论。
标签: ruby arrays pass-by-reference