Tôi đang chơi với Ruby on Rails và tôi đang cố tạo phương thức với các tham số tùy chọn. Rõ ràng có nhiều cách để làm điều đó. Tôi cố gắng đặt tên các tham số tùy chọn là băm, và không xác định chúng. Đầu ra là khác nhau. Hãy xem:Phương thức Ruby và tham số tùy chọn
# This functions works fine!
def my_info(name, options = {})
age = options[:age] || 27
weight = options[:weight] || 160
city = options[:city] || "New York"
puts "My name is #{name}, my age is #{age}, my weight is #{weight} and I live in {city}"
end
my_info "Bill"
-> My name is Bill, my age is 27, my weight is 160 and I live in New York
-> OK!
my_info "Bill", age: 28
-> My name is Bill, my age is 28, my weight is 160 and I live in New York
-> OK!
my_info "Bill", weight: 200
-> My name is Bill, my age is 27, my weight is 200 and I live in New York
-> OK!
my_info "Bill", city: "Scottsdale"
-> My name is Bill, my age is 27, my weight is 160 and I live in Scottsdale
-> OK!
my_info "Bill", age: 99, weight: 300, city: "Sao Paulo"
-> My name is Bill, my age is 99, my weight is 300 and I live in Sao Paulo
-> OK!
****************************
# This functions doesn't work when I don't pass all the parameters
def my_info2(name, options = {age: 27, weight: 160, city: "New York"})
age = options[:age]
weight = options[:weight]
city = options[:city]
puts "My name is #{name}, my age is #{age}, my weight is #{weight} and I live in #{city}"
end
my_info2 "Bill"
-> My name is Bill, my age is 27, my weight is 160 and I live in New York
-> OK!
my_info2 "Bill", age: 28
-> My name is Bill, my age is 28, my weight is and I live in
-> NOT OK! Where is my weight and the city??
my_info2 "Bill", weight: 200
-> My name is Bill, my age is , my weight is 200 and I live in
-> NOT OK! Where is my age and the city??
my_info2 "Bill", city: "Scottsdale"
-> My name is Bill, my age is , my weight is and I live in Scottsdale
-> NOT OK! Where is my age and my weight?
my_info2 "Bill", age: 99, weight: 300, city: "Sao Paulo"
-> My name is Bill, my age is 99, my weight is 300 and I live in Sao Paulo
-> OK!
Cách tiếp cận thứ hai cho tham số tùy chọn là gì? Phương pháp thứ hai chỉ hoạt động nếu tôi không vượt qua bất kỳ tham số tùy chọn nào hoặc nếu tôi vượt qua tất cả.
Tôi đang thiếu gì?
Đây là giải pháp cho vấn đề của tôi. Sau khi đọc lời giải thích của @ texasbruce về việc ghi đè giá trị băm ban đầu, có nghĩa là hợp nhất hàm băm "mặc định" với giá trị băm. Cảm ơn! –
vì 'tùy chọn' sẽ được gán lại, bạn cũng có thể cập nhật tại chỗ:' options.reverse_update (tuổi: 27, trọng lượng: 160, thành phố: "New York") ' – tokland