简体   繁体   中英

"ArgumentError (wrong number of arguments (given 2, expected 1))" for a simple Ruby function

So I'm writing a simple Ruby program, essentially a simple ORM. On my "delete" method, I have written the following:

file = "/Users/john/Projects/csv-orm/20180922-test.csv"

def delete id
  counter = 0
  csv = []

  CSV.foreach(file) do |row|
    counter += 1
    if counter != id
      csv << row
    end
  end

  counter = 0

  CSV.foreach(file, "w") do |row|
    row = csv[counter]
  end
end

delete 2

...and I'm running it in an irb session on my terminal (Mac OS X 10.13, ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]) to test it (for example, by pasting in the code above, and then trying delete 2 , where the number 2 is the argument passed in for the id parameter), and I get the following error:

Traceback (most recent call last):
    4: from /Users/apickle/.rvm/rubies/ruby-2.5.1/bin/irb:11:in `<main>'
    3: from (irb):23
    2: from (irb):19:in `delete'
    1: from /Users/apickle/.rvm/rubies/ruby-2.5.1/lib/ruby/2.5.0/csv.rb:1139:in `foreach'
ArgumentError (wrong number of arguments (given 2, expected 1))

Just to get it out of the way, I have tried testing it in a freshly exited and reopened irb session, and I am typing in require "csv" when I start it up. I'm not sure what to do. :/

EDIT: I've renamed the function to destroy and flfllgpt , and I get the same result - and I have made a simple function that takes a single integer named id and puts s it. That function works. It seems to be somehow related to the CSV calls... when I comment those blocks out, it doesn't throw that to me. But I've used them before, too!

I guess CSV.foreach(file, "w") is the culprit here, because I think what you want to do is open a new file and then write the result? Check this out: https://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html#method-c-foreach

If changing it does not help, can you post the full error message? That makes it easier to identify the error.

It is hard to diagnose the problem without the exact error message, which includes the line number where the error occurs, the method in which the error occurs, the method call for which the error occurs, and the stack trace.

However, there is exactly one place in the code you posted where a method is called with 2 arguments:

CSV.foreach(file, "w") do |row| 
  # …
end

And indeed, the documentation for CSV::foreach clearly says that CSV::foreach only takes one positional argument, this must be the culprit. There simply is no other place in your code that could possibly raise this exception.

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