簡體   English   中英

在迭代哈希值時,在每個迭代器中出現關於Ruby的奇怪行為

[英]Strange ruby on rails behaviour in each iterator, while iterating a hash

我正在使用Ruby on Rails建立一個網站。 我有一個看起來像這樣的常數:

SIZE_CONVERT = {
shoes: {
    men: {
        '1'    => ['32',   '19,7', '32',   '0.5'  ],
        '1.5'  => ['32.5', '20.3', '32.5', '1'    ],
        '2'    => ['33',   '20.6', '33',   '1.5'  ],
        '2.5'  => ['33.5', '21',   '33.5', '2'    ],
        '3'    => ['34',   '21.6', '34',   '2.5'  ]}}}

當我為模型創建一個方法來迭代此哈希時,它的行為很奇怪。 我想返回一個類似於SIZE: 34的字符串,或者只返回No match string。 但是,當我調用此方法時,它不返回字符串,而是返回我所有的SIZE_CONVERT[:shoes][:men]哈希值。

def convert_shoe(gender, size)
    if size.to_f < 3.0
        SIZE_CONVERT[:shoes][gender].each do |s|
            if size == s[1][3]
                "SIZE: " + s[1][2]
            else
                "No match"
            end
        end
    end
end

這是因為您將返回最后一個求值表達式,在這種情況下,將返回


        SIZE_CONVERT[:shoes][gender].each do |s|
            if size == s[1][3]
                "SIZE: " + s[1][2]
            else
                "No match"
            end
        end

[1,2,3,4] .each返回[1,2,3,4],因此SIZE_CONVERT [:shoes] [gender](一個數組)將在.each方法上返回該數組

您可以通過返回比賽來解決此問題


def convert_shoe(gender, size)
    if size.to_f < 3.0
        SIZE_CONVERT[:shoes][gender].each do |s|
            if size == s[1][3]
                return "SIZE: " + s[1][2]
            end
        end
    end
    return "No match"
end

但是最后,雖然做這項工作還不夠,所以您可以使用Array#find方法之類的功能強大的東西,方法是:


def convert_shoe(gender, size)
    if size.to_f < 3.0
        found_size = SIZE_CONVERT[:shoes][gender].find do |s|
            size == s[1][3]
        end
        return "SIZE: " + found_size[1][2] if found_size
    end
    "No match"
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM