0

I need to return to my Rails view more than one variable from method... But how could i do this?

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?

3 Answers 3

2

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

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
Sign up to request clarification or add additional context in comments.

2 Comments

hm, how to get? didn't understand... in view something like = my1.p ? or what?
There's usage scenario in the answer.
0

Use another object that will hold the variables and return it. You can then access the variables from that object;

Comments

0

Array

The easiest way is to return an Array:

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

price, quantity = my1

Hash

But you could also return a 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.

4 Comments

You could use open struct instead of custom object. See my answer.
@SergioTulentsev Thank you, I was not aware of this class.
Hey, you copied my answer! :)
I did not copy that, but I changed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.