Home > Back-end >  Ruby CSV Open - Wrong number of arguments in Ruby 3.0
Ruby CSV Open - Wrong number of arguments in Ruby 3.0

Time:02-23

I am migrating an application from Ruby 2.6 to Ruby 3.0 and am running into an issue opening a CSV file for writing.

The following code worked fine in 2.6.

    CSV.open(csv_path, "wb", {:col_sep => ";"}) do |csv|
      ...
    end

When I move to 3.0 I am getting the error "wrong number of arguments (given 3, expected 1..2)".

I am not seeing anything in Ruby Docs to indicate a change from 2.6

2.6

open( filename, mode = "rb", **options ) { |faster_csv| ... }

3.0

open(file_path, mode = "rb", **options ) { |csv| ... } → object

I see that the CSV library was updated in Ruby 3.0, but am not seeing what could have changed that would cause this code to no longer work.

Any tips would be greatly appreciated.

Edward

CodePudding user response:

In Ruby 3.0, positional arguments and keyword arguments was separated, with deprecation in Ruby 2.7. That means, that the Ruby 2.7 deprecation warning: Using the last argument as keyword parameters is deprecated, ie. using a hash as argument for **options is no longer supported.

You'll have to call it either as:

# Manual spreading hash
CSV.open(csv_path, "wb", **{:col_sep => ";"}) do |csv|
  ...
end

# Or as Keyword argument 

CSV.open(csv_path, "wb", :col_sep => ";") do |csv|
  ...
end

EDIT: See also https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/

  • Related