V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
yxwzaxns
V2EX  ›  Ruby

ruby 的问题,求解

  •  
  •   yxwzaxns · Oct 21, 2015 · 4208 views
    This topic created in 3841 days ago, the information mentioned may be changed or developed.

    a=Array(1..10)

    b=Hash.new

    c=Array.new

    a.map do |e|
    b[:id]=e
    c.push b
    end

    p c

    结果却是
    [{:id=>10}, {:id=>10}, {:id=>10}, {:id=>10}, {:id=>10}, {:id=>10}, {:id=>10}, {:id=>10}, {:id=>10}, {:id=>10}]

    求解

    dalang
        1
    dalang  
       Oct 21, 2015   ❤️ 1
    因为 b 是一个 hash 对象,在循环最后,对象 b 对应的值就是 {:id => 10}. c.push b 是把对象 b 在数组中 insert 了 10 次。
    如果想要预期的结果,可以把循环改成

    ```
    a.map do |e|
    b= Hash.new
    b[:id]=e
    c.push b
    end
    ```
    yxwzaxns
        2
    yxwzaxns  
    OP
       Oct 21, 2015 via Android
    @dalang 非常感谢,一开始学 ruby ,还没有开始习惯它
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1066 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 22:52 · PVG 06:52 · LAX 15:52 · JFK 18:52
    ♥ Do have faith in what you're doing.