简体   繁体   中英

'Wrong number of arguments' error in RUBY

I am trying to build custom string based on data from my class Map .

class Map
  def initialize
    @data = Array.new(3) { Array.new(3, 0) }
  end

  def [](x, y)
    @data[x][y]
  end

  def []=(x, y, value)
    @data[x][y] = value
  end
end

This is how I try to build a string:

def build_map_str(map)
  str = ' '
  (0..2).each do |i|
    (0..2).each do |j|
      str += case map[i][j]
             when 0
               "◻️ "
             when 1
               "❎ "
             when 2
               "🅾️ "
             end
      str += '| ' if i != 2
    end
    str += "\n"
  end
end

And this is how I call this func:

map = Map.new
str = build_map_str(map)

But I am getting in `[]': wrong number of arguments (given 1, expected 2) . How could I fix it?

Given your operator

  def [](x, y)
    @data[x][y]
  end

Your map's elements should be accessed via map[i,j] instead of map[i][j] .

Your definition for Map#[] takes two arguments, so when you call it in build_map_str , it should look like this:

str += case map[i, j]

The same will apply when you assign values:

map[0, 0] = 0

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