【发布时间】:2020-07-19 19:40:36
【问题描述】:
我是 ruby 的新手,我试图将一个数组放入 initialize 方法,但它不能像那样工作,那么如何使用这个参数放置一个数组?谢谢
class User
attr_accessor :name, :friends
def initialize(name, friends)
@name = name
@friends = friends
end
def friendNbr
return friends.count
end
def isFriendWith(value)
friends.each do |user|
if (user.name == value)
return "Yes, #{name} is friend with #{user.name}"
end
end
return "No, #{name} is not friend with #{value}"
end
end
jane = User.new("Jane", [boris, francois, carlos, alice])
bob = User.new("Bob", [jane, boris, missy])
alice = User.new("Alice", [bob, jane])
# bob.isFriendWith("Jane")
# jane.isFriendWith("Alice")
# alice.isFriendWith("Carlos")
【问题讨论】:
-
您的方法存在一个循环问题:您不能在创建用户之前传递它。例如,在创建
alice之前,您将alice作为朋友传递给jane——这是行不通的。您必须先创建用户,一旦创建,您就可以定义友谊。 -
...顺便说一句,
bob.isFriendWith("Jane")是否暗示jane.isFriendWith("Bob")?换句话说,友谊是相互的还是片面的? -
“它不能那样工作”不是一个足够精确的错误描述,我们无法帮助您。 什么不起作用? 如何不起作用?你的代码有什么问题?您收到错误消息吗?错误信息是什么?你得到的结果不是你期望的结果吗?你期望什么结果,为什么,你得到的结果是什么,两者有什么不同?您正在观察的行为不是期望的行为吗?期望的行为是什么,为什么,观察到的行为是什么,它们有何不同?
-
感谢您的回答,首先抱歉,因为我没有描述我的问题/错误,是的,问题来自未分配的变量,我很困惑,因为我使用 DB/SQL 进行编码approch,这就是为什么它不起作用,谢谢
标签: arrays ruby methods initialization arguments