0

私の問題は、Rubyで参照を渡すことができないという事実にあります。私には2つの関数searchingとがありget_title_idsます。

私は2つのアレイを持っています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 定義されていることです。titlehrefsearching

電話をかけるたびにget_title_ids、以前に収集したデータを収集したくありません(したがってstart_form)。

私の問題は記憶ではなく時間です。get_title_ids したがって、前のforループで既にスクラップしたデータをスクラップする時間を無駄にする必要があるという事実と比較して、関数を呼び出すときにデータが複製されることについてはあまり心配していません。

したがって、Rubyで参照によってパスをハックする方法を知っている人はいますか。

編集

returnしたがって、以下の質問を読むと、 fromを実行する必要がないことがわかりますget_title_ids。そして、それはすべてうまくいきました。

4

2 に答える 2

2

ruby の配列は、最も確実に参照によって渡されます (技術的には、配列は値によって渡されますが、その値は配列へのポインターです)。観察:

def push_new ary
  ary << 'new element'
end

a = ['first element']
push_new a
a # => ["first element", "new element"]
于 2012-06-28T20:40:36.347 に答える
1

参照型オブジェクトが値で渡された場合でも、メモリ内の同じオブジェクトを参照しています。そうでない場合は、以下の例は機能しません。

例:

> 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"]
于 2012-06-28T20:43:03.807 に答える