我正在创建一个非常简单的“存储库”作为我的第一个真正的ruby脚本。我创建了人们可以创建项目和起始值的部分,但我似乎无法确定如何使人们不能递增(或递减)0或负数。
我要添加的代码如下:
class Item
attr_accessor :name, :count
def initialize (name,initCount )
@name=name.downcase
@count=initCount
end
def add(amount)
@count += amount
end
def sub(amount)
@count -= amount
end
end
def prompt()
puts @items.inspect
puts " (A)dd item\n (R)emove item\n (L)ist items\n (I)ncrease item\n (D)ecrease items\n (Q)uit "
select = [(print '?: '), gets.rstrip][1]
if (select.upcase=="A") then
puts "Add Item\nItem name"
name=[(print 'Name? : '), gets.rstrip][1]
puts "Initial Count"
count= [(print 'Count? : '), gets.rstrip][1]
@items.push(Item.new(name,count.to_i)) unless @items.index(@items.find { |l| l.name == name })
end
感谢任何帮助。
答案 0 :(得分:1)
考虑像这样组织你的代码。我可能犯了一些错误,但你会明白这一点。
PROMPT_TEXT =
" (A)dd item
(R)emove item
(L)ist items
(I)ncrease items
(D)ecrease items
(Q)uit ?: "
ILLEGAL_PROMPT_RESPONSE_MSG =
"You can't enter that! What were you thinking??"
NEGATIVE_NUMBER_MSG =
"If I've told you once, I've told you a thousand times: NO NEGATIVE NUMBERS!"
NOT_NUMBER_MSG =
"If that's a number, it must be Roman, and they aren't allowed."
TRY_AGAIN_MSG = "Try again...
。
def prompt()
loop do
puts @items.inspect # What's this?
puts PROMPT_TEXT
gets.rstrip.upcase case
when "A"
break if add_item
when "R"
...
when "L"
...
...
when "Q" then return
else
puts ILLEGAL_PROMPT_RESPONSE_MSG
end
puts TRY_AGAIN_MSG
end
end
def add_item
puts "Add Item\nItem name"
print 'Name? : '
name = gets.rstrip
puts "Initial Count"
print 'Count? : '
count = gets.rstrip
unless count =~ /\d+/
if count =~ /-\s*\d+/
puts NEGATIVE_NUMBER_MSG
else
puts NOT_NUMBER_MSG
end
return false
end
@items.push...
true
end
旁白:陈述
name=[(print 'Name? : '), gets.rstrip][1]
让人想起一个以“abomin”开头并以“ation”结尾的单词。 : - )
答案 1 :(得分:-1)
class Item
attr_accessor :name, :count
def initialize (name,initCount )
raise if initCount<0
@name=name.downcase
@count=initCount
end
def add(amount)
raise if amount<0
@count += amount
end
def sub(amount)
raise if amount<0 || amount>@count
@count -= amount
end
end