rubyrubygems

My two code snippet use the exact map! function but are acting differently


I am working on the basic mastermind project with random selection of colours and user have to guess it.

The problem is map! is supposed to go via each element and map! edits the values of the original array. But here in the first it does work as intended by changing its numerical values to a hash based value where each number represents a color like this:

module Shapes
  CIRCLE = "●"
  COLORS = {
    1 => :red,
    2 => :green,
    3 => :magenta,
    4 => :blue,
    5 => :cyan,
    6 => :yellow,
    8 => :white,
    9 => :black
}
end

There are two codes where one takes values from a random function and the other user inputs. with the second one the values are [nil,nil,nil,nil] which doesn't make sense. Help me fix the issues with what I'm doing wrong with the map! function.

The code in my main.rb

  def random_code
    arr = Array.new(4) {(rand(1..6).to_i)}
    puts arr
    arr.map! do |item|
      color = COLORS[item]
      CIRCLE.colorize(color)
    end
    puts arr
    return arr
  end
end

My other code inside another module

      p_code.map! do |item|
        colors = COLORS[item.to_i]
        CIRCLE.colorize(colors)
        puts CIRCLE.colorize(colors)
      end```

Solution

  • puts returns nil which alters your method's behavior. For debugging purposes, there's p which doesn't alter the return value. It also prints the value in its literal form (if possible) which makes it easier to distinguish integers, string, symbols and nil.

    A simple example:

    a = "1"
    a #=> "1"
    

    With p:

    a = p "1"
    # "1"       <- prints quotes
    a #=> "1"   <- retains return value
    

    as opposed to puts:

    a = puts "1"
    # 1          <- omits quotes
    a #=> nil    <- nil return value
    

    You can usually just prefix an expression with p to print it. However, for complex or multi-line expressions, you might have to add parentheses, i.e. p( ... ).


    Regarding your code: the to_i call is superfluous because rand(1..6) already returns an integer. In addition, you could move your map! logic right into the Array.new block: (no explicit return is needed)

    def random_code
      Array.new(4) do
        color = COLORS[rand(1..6)]
        CIRCLE.colorize(color)
      end
    end