Home Rails Console Argument Error Creating a New object
Reply: 1

Rails Console Argument Error Creating a New object

miner27
1#
miner27 Published in 2018-01-12 21:10:45Z

I am new to Rails and Ruby development but I am trying to create an object called Currency which takes in two params and does some calculations on them. I am using attr_accessor to set up the params and I put the file inside the lib directory.

Whenever I run rails console and try to do c = Currency.new(100, "CAD") I get the following error:

ArgumentError: wrong number of arguments (given 2, expected 0)
from (irb):5:in `initialize'
from (irb):5:in `new'
from (irb):5

I did make sure to include the file in application.rb. Here is a skeleton of my class:

class Currency
  class << self
    attr_accessor :input_value, :currency_iso

    USD_ISO = "USD"
    USD_TO_DM = 2.8054

    def converted_value
     convert_to_dm
    end

    private

    def convert_to_dm
     @input_value / USD_TO_DM
    end
  end
end

I have looked all over and I am stumped on what this issue may be. I have tried with and without an initialize method and I have tried creating a more basic version.

JesusTinoco
2#
JesusTinoco Reply to 2018-01-13 09:00:26Z

The problem here is that you are defining the method as a class method. And you are not defining the initialize method with those two params. Let's check the code below:

class Currency
  attr_accessor :input_value, :currency_iso

  USD_ISO = "USD"
  USD_TO_DM = 2.8054

  def initialize(input_value, currency_iso)
    @input_value = input_value
    @currency_iso = currency_iso
  end

  def converted_value
    convert_to_dm
  end

  private

  def convert_to_dm
    input_value / USD_TO_DM
  end
end

Also, due to you have already defined the attr_accessor you don't need to use the @ when calling those attributes.

I found this post. It can help you to understand better the difference between class method and instance method.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299272 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO