繁体   English   中英

如何使用 Ruby 属性模板、shop_items 和 date 来完成所需的任务?

[英]How do I use the Ruby attributes template, shop_items, and date to do the required tasks?

非常感谢您的帮助,因为我对如何使用这些属性感到困惑。 在此处输入图像描述

require 'erb'

class ShoppingList
  attr_reader :template
  attr_reader :shopping_items
  attr_reader :date

  def initialize(shopping_items, template, date = Time.now)
    @template = template
    @shopping_items = shopping_items
    @date = date
  end

  def output(output_file)
    File.write(output_file, render)
  end

  private

  def render
    ERB.new(@template).result(binding)
  end
end

def shopping_items
  ["milk", "egg", "ham", "bread"]
end

def template
  %{
    <html>
    <head></head>
    <body>
    <h1> Shopping List for <%= @date.strftime('%A, %d, %B, %Y')%></h1>
    <p> You need to buy </p>
    <ul>
      <% @shopping_items.each do |item| %>
        <li><%= item %></li>
      <% end %>
    </ul>
    </doby>
    </html>
  }
end

ShoppingList.new(shopping_items, template).output('shopping_list.html')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM