Gus Andrianos Gus Andrianos - 6 months ago 10
Ruby Question

NoMethodError while I defined it using metaprogramming

I am working on some code. I am trying to print a list of sample colors using a gem that I created and it throws a

NoMethodError

I am opening the String class and I am doing that.

def self.sample_colors
@@colors_arr.each do |color|
puts "This is #{color}".color
end
end


It is supposed to be working because
.color
should change to ever color the array has so, first loop would be
.red
then
.blue
and so on.
This code is taking care of creating the method for each color.

def self.create_colors
@@colors_arr.zip(@@color_codes).each do |color,code|
self.send(:define_method,color) do
"\e[#{code}m#{self}\e[0m"
end
end
end


Any thoughts?
Edit: If I use
.red
or
.blue
it works, I just don't get why that works and this one isn't

Answer

The problem is with

puts "This is #{color}".color

You are basically calling a method color every time. Ruby does not care about the fact you have a local variable called color.

You want to define sample_colors as:

def self.sample_colors
  @@colors_arr.each do |color|
    puts "This is #{color}".send(color)
  end
end

The send method will call the method name represented by a given string/symbol on the object.

Comments