[Ruby] Map and return?

Hôm nay nhận được 1 câu hỏi đến từ vị trí của CườngNĐ, mình vẫn chưa tìm hiểu lý do tại sao lại có kết quả khác nhau như vậy. Viết đây để nhớ, mai mốt tìm ra lý do rồi update lại bài blog này

Câu hỏi:

# ruby
arr =[[1,2], [3,4], [5,6]]
arr.map{|a,b| return a if a + b > 10}

#> LocalJumpError (unexpected return)
Nếu đổi lại thế này
arr.map{|a,b| a if a + b > 10}
#> [nil, nil, 5]

Và nếu để vào method như thế này

# ruby


def test_arr
  arr =[[1,2], [3,4], [5,6]]
  arr.map{|a, b| return a if a + b > 10}
end

#> 5

Tại sao nhỉ?

Lê Hoàng Tâm (Tom Le) is a Software Engineer and Cloud Architect with over 10 years of experience. AWS Certified. Specializes in distributed systems, DevOps, and AI/ML integration. Founder of Th?nk And Grow — a platform sharing practical technology insights in Vietnamese. Passionate about building scalable systems and helping developers grow through real-world knowledge.