请举个例子,我是新来的返回成分的数量。对ruby不熟悉并且有语法概率。
class Recipe
include Enumerable
attr_reader :name
def initialize(name, cuisine, ingredients, steps)
@name = name
@cuisine = cuisine
@ingredients = ingredients
@steps = steps
end
def name
@name
end
def cuisine
@cuisine
end
def ingredients
@ingredients
end
def steps
@steps
end
def display
puts "Recepie Manager"
puts "\n Name:", @name, "\n Cuisine:", @cuisine ,"\n Ingredients and Quantity:", @ingredients, "Steps:", @steps
end
def how_many_ingredients
puts "Number of Ingridents:" , @ingredients
end
end
obj1 = Recipe.new('Briyani', 'Indian','chicken,rice,spices,blah,blah','cook and eat')
obj1.display
答案 0 :(得分:0)
从代码中看起来您错放了end
语句。你必须在结束后创建类的对象。
class Receipe
include Enumerable
attr_reader :name
def initialize(name, cuisine, ingredients, steps)
@name = name
@cuisine = cuisine
@ingredients = ingredients
@steps = steps
end
def name
@name
end
def cuisine
@cuisine
end
def ingredients
@ingredients
end
def steps
@steps
end
def display
puts "Recepie Manager"
puts "\n Name:", @name, "\n Cuisine:", @cuisine ,"\n Ingredients and Quantity:", @ingredients, "Steps:", @steps
end
def how_many_ingredients
puts "Number of Ingridents:" , @ingredients
end
end
obj1 = Receipe.new('Briyani', 'Indian','chicken,rice,spices,blah,blah','cook and eat')
obj1.display
答案 1 :(得分:0)
谢谢,
我使用了我的大师" Google"寻找解决方案。为了返回成分计数,我使用了分割和计数方法。
def how_many_ingredients
ingredients = @ingredients.split(",")
puts "Number of Ingridents:" , ingredients.count
end
答案 2 :(得分:0)
你可以使用gets.chomp
来获取用户的意见,如果这就是你的意思
类Receipe 包括可枚举 attr_reader:name
def initialize(name, cuisine, ingredients, steps)
@name = name
@cuisine = cuisine
@ingredients = ingredients
@steps = steps
end
def name
@name
end
def cuisine
@cuisine
end
def ingredients
@ingredients
end
def steps
@steps
end
def display
puts "Recepie Manager"
puts "\n Name:", @name, "\n Cuisine:", @cuisine ,"\n Ingredients and Quantity:", @ingredients, "Steps:", @steps
end
def how_many_ingredients
puts "Number of Ingridents:" , @ingredients
end
end
yourname = gets.chomp
yourcuisine = gets.chomp
youringridents = gets.chomp
yoursteps = gets.chomp
obj1 = Receipe.new(yourname, yourcuisine,youringridents,yoursteps)
obj1.display