Jason Milam
Jason Milam

Reputation: 111

Ruby method in rails application

I have a method that I created that does some calaculation's based on an integer passed as a parameter. When I add the method to my view it only outputs the last variable.

Budget.rb(model)

def self.percent_calculate(question)
    reception = question * 0.5
    ceremony = question * 0.03
    clothes = question * 0.1
    flowers = question * 0.1
    entertain = question * 0.1
    photo = question * 0.12
    rings = question * 0.03
    misc = question * 0.02
end

index.html.erb(View)

<%= Budget.percent_calculate(5000.to_i) %>

Output from this looks is: 150.0, which is the calculation of the misc variable.

I want to output each variable out separately one after the other.

Upvotes: 0

Views: 63

Answers (2)

atw13
atw13

Reputation: 719

Every method in Ruby returns the value of the last statement in the method, which is why you're getting misc.

You're saying you want to output each variable. You either need separate methods, or you need to return some kind of array, object, or hash that compacts all the data you're trying to use. For example, this would return a hash:

def self.percent_calculate(question)
{:reception => question * 0.5,
  :ceremony => question * 0.03,
  :clothes => question * 0.1,
  :flowers => question * 0.1,
  :entertain => question * 0.1,
  :photo => question * 0.12,
  :rings => question * 0.03,
  :misc => question * 0.02}
end

And then you could access it like

calculations = percent_calculate(question)
calculations[:reception]

to get the reception value.

Upvotes: 1

jvnill
jvnill

Reputation: 29599

ruby only returns the last line of the method unless you call return in the middle of the method. That said, you'd want to separate your calculation to different methods and call them 1 by 1. With some metaprogramming, this can be achieved by

CALCULATION_PERCENTAGES = {
  reception: 0.5,
  ceremony: 0.03,
  clothes: 0.1,
  flowers: 0.1,
  entertain: 0.1,
  photo: 0.12,
  rings: 0.03,
  misc: 0.02
}

class << self
  CALCULATION_PERCENTAGES.each do |cp, weight|
    define_method "#{cp}_value" do |question|
      weight * question
    end
  end
end

Then you can just call

<%= Budget.reception_value 5000 %>
<%= Budget.ceremony_value 5000 %>

Upvotes: 2

Related Questions