【问题标题】:How to work around the unavailibilty of passing by reference in ruby?如何解决在 ruby​​ 中无法通过引用传递的问题?
【发布时间】:2012-06-28 20:31:26
【问题描述】:

我的问题是我无法在 Ruby 中通过引用传递。 我有两个函数searchingget_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 中定义的数组titlehref

每次我打电话给get_title_ids 我都不想收集我之前收集的数据(因此是 start_form)。

我的问题不是记忆而是时间。所以我不太担心在调用get_title_ids 函数时数据被复制,而不是我不得不浪费时间来报废我在前一个 for 循环中已经报废的数据。

那么有谁知道如何在 Ruby 中通过引用破解 pass。

编辑

通过阅读以下问题,我发现我不需要从get_title_ids 执行return。然后一切都奏效了。

【问题讨论】:

  • 即使一个引用类型的对象通过值传递,它仍然是引用内存中的同一个对象。
  • 太棒了!这样我就可以避免内存重复:),但是我如何 push 数组中的元素通过值/引用传递
  • @seleniumnewbie:看我的回答:)
  • 我认为这里的问题不是因为引用,而是因为你不知道如何使用迭代器。
  • @megas,我认为迭代器很好。是 return 搞砸了。感谢您的评论。

标签: ruby arrays pass-by-reference


【解决方案1】:

ruby 中的数组肯定是通过引用传递的(从技术上讲,它们是通过值传递的,但该值是指向数组的指针)。观察:

def push_new ary
  ary << 'new element'
end

a = ['first element']
push_new a
a # => ["first element", "new element"]

【讨论】:

  • 这就是我所做的,但长度保持不变,因此以您的示例为例。我的a 现在是a=&gt; ["new element"]
  • 你是什么意思,“长度保持不变”?你需要它是一样的吗?那么你是如何通过丢弃旧元素来添加新元素的呢?
  • 好吧,我不希望旧的被丢弃,但他们是。我猜问题是最后一个return,它导致了所有问题。谢谢你的帮助。将您的解决方案标记为答案,因为除了指出正确的方向之外,您是第一个回复的人。
  • 不,在 Ruby 中,一切都是按值传递和分配的。对象不是值。所有值都是参考。
  • 您仔细阅读我的回答了吗? :) 此外,并非所有值都是引用。
【解决方案2】:

即使一个引用类型的对象是按值传递的,它仍然是在引用内存中的同一个对象。如果不是这种情况,那么下面的示例将不起作用。

示例:

> 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"]

【讨论】:

    猜你喜欢
    • 2014-02-09
    • 2017-01-05
    • 2012-01-07
    • 2011-03-14
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2015-08-09
    • 2011-11-01
    相关资源
    最近更新 更多