大批
最简单的方法是返回一个Array:
def my1
@qnt = 2
@price = 1
[ @price, @qnt ]
end
price, quantity = my1
哈希
但你也可以返回一个Hash:
def my1
@qnt = 2
@price = 1
{ :quantity => @qnt, :price = @price
end
return_value = my1
price = return_value[:price]
quantity = return_value[:quantity]
# or
price, quantity = [ return_value[:price], return_value[:quantity] ]
自定义类
或自定义类:
class ValueHolder
attr_reader :quantity, :price
def initialize(quantity, price)
@quantity = quantity
@price = price
end
end
def my1
@qnt = 2
@price = 1
ValueHolder.new(@qnt, @price)
end
value_holder = my1
price = value_holder.price
quantity = value_holder.quantity
# or
price, quantity = [ value_holder.price, value_holder.quantity ]
开放结构
您可以像Sergio 提到的那样使用OpenStruct。