局部变量vs实例变量Ruby初始化

时间:2015-02-01 14:22:53

标签: ruby initialization

我在Ruby上有一个班级,我传递了商品价格的哈希。它们的形式为

{"date (string)" => price (float), etc, etc}

在初始化方法中,我将日期转换为Dates,如下所示:

@data = change_key_format(日期)

但我注意到那个方法似乎也改变了原来的论点。这是为什么?这是代码:

def initialize(commodity_name, data)
    puts "creating ...#{commodity_name}"
    @commodity_name = commodity_name
    @data = change_hash_keys_to_dates(data)
    @dates = array_of_hash_keys(data)
    puts data ######## UNCHANGED
    @data = fix_bloomberg_dates(@data, @dates)
    puts data ######## CHANGED -------------------- WHY???
    #get_price_data
end


def fix_bloomberg_dates(data, dates)
    #Fixes the bad date from bloomberg  
    data.clone.each do |date, price|

        #Looks for obvious wrong date
        if date < Date.strptime("1900-01-01")
            puts dates[1].class
            date_gap = (dates[1] - dates[2]).to_i


            last_date_day = dates[1].strftime("%a %d %b")
            last_date_day = last_date_day.split(" ")
            last_date_day = last_date_day[0].downcase

            #Correct the data for either weekly or daily prices
            #Provided there are no weekend prices
            if date_gap == 7 && last_date_day == "fri"
                new_date = dates[1] + 7
                data[new_date] = data.delete(date)
            elsif date_gap == 1  && last_date_day == "thu"
                new_date = dates[1] + 4
                data[new_date] = data.delete(date)
            else
                new_date = dates[1] + 1
                data[new_date] = data.delete(date)
            end         
        end
    end

    return data
end

def change_hash_keys_to_dates(hash)
    hash.clone.each do |k,v|
        date = Date.strptime(k, "%Y-%m-%d")

        #Transforms the keys from strings to dates format
        hash[date] = hash.delete(k)
    end
    return hash
end

def array_of_hash_keys(hash)
    keys = hash.map do |date, price|
        date
    end
    return keys
end

1 个答案:

答案 0 :(得分:3)

由于这些原因:

data[new_date] = data.delete(date)

您正在修改原始data对象。如果您不想这样做,请创建对象的副本:

data2 = data.clone

然后在方法中将data的所有其他引用替换为data2(包括return data2)。