Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby方法返回多个变量_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails Ruby方法返回多个变量

Ruby on rails Ruby方法返回多个变量,ruby-on-rails,ruby,Ruby On Rails,Ruby,我需要从方法返回到Rails视图中的多个变量。。。但我怎么能做到这一点呢 比如现在我有 def my1 @price = 1 @price end 但我怎么能同时返回其他值,比如: def my1 @qnt = 2 @price = 1 @price, @qnt end ? 另外,我的想法是把它们像绳子一样分开 @price + "/-/" + @qnt 然后通过视图中的/-/将其拆分。。。。但这是一个坏习惯。。。 那么如何从一个方法中获得两个或多个变量呢?返回一个数组: def

我需要从方法返回到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

使用另一个将保存变量并返回它的对象。然后可以从该对象访问变量

排列 最简单的方法是返回:

搞砸 但您也可以返回:

自定义类 或自定义类:

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 ]
OpenStruct
您可以使用as。

hm,如何获取?我不明白。。。在视图中,类似于=my1.p?或者什么?答案中有使用场景。你可以使用开放结构而不是自定义对象。看看我的答案。@SergioTulentsev谢谢,我不知道这门课。嘿,你抄了我的答案!:)我没有抄,但我改了。
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 ]