Каков возврат блока yield при вызове параметра, связанного с методом из Gem, повторяемого с #each? - PullRequest
1 голос
/ 22 сентября 2019

Я пытаюсь понять метод, используемый в игре Mastermind, и я не понимаю, что производит блок yield;или возврат фактического метода ...

Вот код:

#lib/mastermind/gameboard.rb

require 'colorize'

def colorize(set, is_color_code)
  colors = []
  text = is_color_code ? "0" : "."
  set.colors.each { |color| colors.push(text.public_send(color.to_sym)) }
  colors.join(' ')
end

Мой основной вопрос: если #colors возвращает массив всех ключей из хеша, иЯ просто помещаю локальную переменную text в локальный массив colors, объединенный с #public_send(color.to_sym), не будет ли возвращаемый метод #colorize здесь массивом "0" .color или ".«.color?

Я думаю, нужно сказать, что #colorize - это метод в Colorize Gem, однако этот #colorize метод является частью отдельного класса в проекте I 'м рецензии.

1 Ответ

3 голосов
/ 22 сентября 2019

Давайте разберем метод построчно, чтобы увидеть, что происходит.

def colorize(set, is_color_code)
  colors = [] # instantiate an array
  text = is_color_code ? "0" : "."  # ternary assignment if is_color_code == true || false
  # set.colors is an array of strings like ['white', 'white', 'white', 'white']
  # set.colors.each { |color| colors.push(text.public_send(color.to_sym)) }
  # line above this refactored to comment
  set.colors.each do |color|
    # color.to_sym # convert the string to symbol so 'white' becomes :white
    # you must pass a symbol to public_send 
    # so this is sending the name of the color to the string as provided by the gem.
    colors.push( text.public_send(color.to_sym) ) # push the return of that into array
  end 
  # In Ruby the method always returns whatever the output of the last line returns.
  colors.join(' ') # returns the colors array a string joined by spaces
end

В этом случае метод colorize определен внутри класса GameBoard.Поэтому, когда этот метод вызывается для экземпляра GameBoard, он будет вести себя так, как было определено.Где, как 'blue'.colorize(:blue) здесь .colorize метод расширяет класс String, чтобы ответить с помощью цветовых кодов переданного символа цвета

Пример

'blue'.colorize(:blue) # same as 'blue'.blue
 =>"\e[0;34;49mblue\e[0m"

Рефакторированная версия

def colorize(set, is_color_code)
  text = is_color_code ? "0" : "."
  set.colors
     .map { |color| text.public_send(color.to_sym) }
     .join(' ')
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...