简体   繁体   中英

Rails Console Argument Error Creating a New object

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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