简体   繁体   中英

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

I'm making a website with Ruby on Rails. I have a constant that looks like this:

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'  ]}}}

When I create a method for a model that iterates this hash, it behaves strange. I want to return a string that looks like SIZE: 34 for example, or just return me No match string. But when I call this method it doesn't return a string, it returns all my SIZE_CONVERT[:shoes][:men] hash.

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

This is because you are returning the last evaluated expression, on this case is the return of


        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 returns [1,2,3,4], so SIZE_CONVERT[:shoes][gender] (an array) will return that array on .each method

You can fix this by returning on the match


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

But the last, while is doing the job, is not enough rubyist, you can use functional cool things such Array#find method, this way:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM