DEV Community

Edward Smith-Silvia
Edward Smith-Silvia

Posted on • Updated on

Making Sense of Send

send() is an instance method which is used to pass a message to an object. In my case, there were methods that I did not want it to pass. It is currently the end of phase 1 in my bootcamp and I spent this week creating a Pokedex CLI using the Pokeapi.

response.each do |key, value|
    self.class.attr_accessor(key) unless key == "abilities"
    self.send("#{key}=", value) unless key == "abilities"
Enter fullscreen mode Exit fullscreen mode

While creating my Ruby CLI project, I ran into the issue of .send overriding my method and storing the wrong data.

Through lots of troubleshooting, it finally occurred that the attr_accessor, used to create reader and writer methods, took a key and created a method for it, was sending the self made abilities method to the Pokemon object and hardcoding its own value. In order to fix this we use unless to prevent the method from being created so it can be written later.

    def abilities
        @abilities.collect do |a_hash|
Enter fullscreen mode Exit fullscreen mode

By preventing attr_accessor and send from creating the abilities method, I am able to look deeper into the hash and pick out exactly what I want, in this case, the value (ability) for ["name"] to be returned to the user when selecting a Pokemon to learn more about. The same was done for other attributes such as the ["type"] with the end result appearing like this.

NAME - Venusaur
ABILITIE(S) - overgrow, chlorophyll
TYPE(S) - grass, poison
Enter fullscreen mode Exit fullscreen mode

to prevent other methods from being overridden we would add an || and repeat the unless process. The alternative and simpler route however, would be to manually use the attr_accessor rather than automating it. Who wouldve guessed it? Obviously not me.

Top comments (0)