简体   繁体   中英

wrong number of arguments (given 1, expected 2) (ArgumentError)

My goal is for a user to enter their screen resolution and store it in screen_size . I did this, but I have an error.

class Screen
  attr_accessor :screen_size, :info

  def initialize(screen_size, info)
    @screen_size = screen_size
    @info = info
  end
end

my_info = Screen.new("What is you're resolution?")
my_screen = Screen.new(gets.chomp)
# >> in `initialize': wrong number of arguments (given 1, expected 2) (ArgumentError)

How can I solve this?

You are passing wrong arguments to Screen.new . Your initialize method expects two arguments and you are passing only one.

Try this:

screen = Screen.new(gets.chomp, "What is you're resolution?")

gets.chomp returns one value (which is whatever you typed in before pressing enter). That method expects two. If you're entering something like "1024 768", then you could split the input by the space. Something like this:

w, h = gets.chomp.split(' ')
my_screen = Screen.new(w, h)

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