[英]Ruby method return more than one variable
我需要從方法中返回多個Rails視圖...但是我該怎么做?
例如現在我有
def my1
@price = 1
@price
end
但是我怎么還可以返回其他值呢?
def my1
@qnt = 2
@price = 1
@price, @qnt
end
?
另外我的想法是將它們拆分為字符串
@price + "/-/" + @qnt
然后僅通過/-/將它們拆分為視圖。...但這是一個不好的做法...那么我怎么能從一個方法中獲得兩個或多個變量?
返回一個數組:
def my1
qnt = 2
price = 1
[price, qnt]
end
那么您可以執行以下操作:
p, q = my1() # parentheses to emphasize a method call
# do something with p and q
或者,您可以返回一個自定義對象,如下所示:
require 'ostruct'
def my1
qnt = 2
price = 1
OpenStruct.new(price: price, quantity: qnt)
end
res = my1() # parentheses to emphasize a method call
res.quantity # => 2
res.price # => 1
使用將保存變量並返回它的另一個對象。 然后可以從該對象訪問變量。
最簡單的方法是返回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 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.