简体   繁体   English

Ruby方法返回多个变量

[英]Ruby method return more than one variable

I need to return to my Rails view more than one variable from method... But how could i do this? 我需要从方法中返回多个Rails视图...但是我该怎么做?

For example now i have 例如现在我有

def my1
 @price = 1
 @price
end

but how could i also return other valuem somethin like: 但是我怎么还可以返回其他值呢?

def my1
 @qnt = 2
 @price = 1
 @price, @qnt
end

?

Also my idea is to split them to string like 另外我的想法是将它们拆分为字符串

@price + "/-/" + @qnt

and then just split them via /-/ in view.... But this is a bad practice... So how could i get from one method two or more variables? 然后仅通过/-/将它们拆分为视图。...但这是一个不好的做法...那么我怎么能从一个方法中获得两个或多个变量?

Return an array: 返回一个数组:

def my1
 qnt = 2
 price = 1
 [price, qnt]
end

then you can do this: 那么您可以执行以下操作:

p, q = my1() # parentheses to emphasize a method call
# do something with p and q

Option 2 选项2

Or you can return a custom object, like this: 或者,您可以返回一个自定义对象,如下所示:

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

Use another object that will hold the variables and return it. 使用将保存变量并返回它的另一个对象。 You can then access the variables from that object; 然后可以从该对象访问变量。

Array 数组

The easiest way is to return an Array : 最简单的方法是返回Array

def my1
  @qnt = 2
  @price = 1
  [ @price, @qnt ]
end

price, quantity = my1

Hash 杂凑

But you could also return a Hash : 但是您也可以返回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] ]

Custom Class 自定义类

Or a custom Class: 或自定义类:

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 开放结构

You could use OpenStruct as Sergio mentioned . 您可以使用Sergio提到的 OpenStruct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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