Reputation: 8548
My problem is around the fact that I cannot pass by reference in Ruby.
I have two functions searching
and get_title_ids
.
I have two arrays in searching
(1) title (2) href
which needs to be updated.
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
The problem is I am unable to push
new elements into the arrays title
and href
that have been defined in searching
.
Each time I call get_title_ids
i do not want to gather data that I had previously gathered(hence the start_form).
My problem is not memory but time. So i am not too concerned about the data being duplicated when I call the get_title_ids
function as compared to the fact that I have to waste time scrapping data that I already scrapped in the previous for loop.
So does any one know how to hack the pass by reference in Ruby.
SO from reading the questions below turns out I dint need to perform the return
from get_title_ids
. And then it all worked.
Upvotes: 0
Views: 91
Reputation: 61520
Even if a reference type object is passed by value, it is still referring to the same object in memory. If this were not the case then the example below would not work.
example:
> def searching
> title = []
> href = []
> test(title, href)
> puts "Title: #{title.inspect} Href: #{href.inspect}"
> end
> def test(title, href)
> title << "title1"
> title << "title2"
> href << "www.title1.com"
> href << "www.title2.com"
> end
> searching
Title: ["title1", "title2"] Href: ["www.title1.com", "www.title2.com"]
Upvotes: 1
Reputation: 230461
Arrays in ruby are most certainly passed by reference (well, technically, they are passed by value, but that value is a pointer to the array). Observe:
def push_new ary
ary << 'new element'
end
a = ['first element']
push_new a
a # => ["first element", "new element"]
Upvotes: 2