繁体   English   中英

Ruby方法返回多个变量

[英]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

选项2

或者,您可以返回一个自定义对象,如下所示:

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.

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