require 'date'
#
# 定义常量 MY_BOOK
#
# @param [Array]
MY_BOOK = [
{
title: '台湾自助游参考手册',
describe: '从此告别跟团的强制购物',
book_type: '1',
price: '50',
published_at: '2014-01-01 01:01:01'
},
{
title: 'Ruby完全入自学册',
describe: 'Ruby入门必读精品',
book_type: '2',
price: '75',
published_at: '2015-02-02 02:02:02'
},
{
title: '军事基础',
describe: '军事迷必备书籍',
book_type: '3',
price: '100',
published_at: '2016-03-03 03:03:03'
}
]
class Book
#
# 初始化方法
# @param [String] title 标题
# @param [String] describe 描述
# @param [String] book_type 书籍类型
# @param [String] price 书籍价格
# @param [String] published_at 发表时间
#
# @return [Object] 实例对象
#
def initialize(title = '', describe = '', book_type = '0', price = '0', published_at = '')
@title = title
@describe = describe
@book_type = book_type.to_i
@price = price.to_i
@published_at = published_at
end
#
# @param [Array] 书籍信息 数组包Hash
#
# @return [Object] 3个实例对象
#
def self.create_some_books(args)
book1 = ::Book.new(args[0][:title], args[0][:describe], args[0][:book_type], args[0][:price], args[0][:published_at])
book2 = ::Book.new(args[1][:title], args[1][:describe], args[1][:book_type], args[1][:price], args[1][:published_at])
book3 = ::Book.new(args[2][:title], args[2][:describe], args[2][:book_type], args[2][:price], args[2][:published_at])
return book1, book2, book3
end
#
# 返回价格等级
#
# @param [Integer] 价格
#
# @return [String] 价格等级
#
def price_level
if @price < 60 && @price > 0
return '低价位'
elsif @price >= 60 && @price < 90
return '中价位'
elsif @price >= 90
return '高价位'
end
end
#
# 返回book类型
# @param [Integer] 1~3
#
# @return [String] 书籍类型
#
def type_name
case @book_type
when 1
return '1是旅游类'
when 2
return '2是技术类'
when 3
return '3是军事类'
else
return '暂无定义'
end
end
#
# 循环判断书籍价格 计算价格大于等于60的总数
# @param [String] 价格
#
# @return [Float] 总价
#
def self.high_price_book_price
$price_sum = 0
(0 ... MY_BOOK.length).each do |i|
if MY_BOOK[i]['price'].to_i >= 60
$price_sum += MY_BOOK[i]['price'].to_i
end
end
return $price_sum.to_f
end
#
# 循环判断书籍价格, 计算价格大于等于60的平均价格
# @param [String] 价格
#
# @return [Float] 平均价格
#
def self.avg_price
$price_avg = 0
$book_count = 0
(0 ... MY_BOOK.length).each do |i|
if MY_BOOK[i][:price].to_i >= 60
$price_avg += $price_avg + MY_BOOK[i][:price].to_i
$book_count = $book_count + 1
end
end
return $price_avg.to_f / $book_count
end
#
# 返回某年某月最后一天
#
# @param [Integer]] 年
# @param [Integer] 月
#
# @return [Date] 最后一天的日期
#
def self.month_end(year, month)
date_result = Date.civil(year, month, -1)
return date_result.day
end
ß
#
# 返回特定格式时间
#
# @param [String] 2016-03-03 03:03:03
#
# @return [String] 2016年03月03日
#
def published_at_cn
date = Date.parse(@published_at)
date.year.to_s + '年' + date.month.to_s + '月' + date.day.to_s + '日'
end
end
# 实例三个对象
@b1, @b2, @b3 = Book.create_some_books(MY_BOOK)
puts @b1.price_level
puts @b1.type_name
puts "大于60总价#{Book.high_price_book_price}"
puts "特定格式日期#{@b1.published_at_cn}"
puts "大于60平均价格#{Book.avg_price}"
puts "最后一天为#{Book.month_end(2016, 2)}"