Reputation: 13
im new with ruby and i tried to put an array into initialize method but its not work like that, so how to put an array with this argument ? thanks
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")
Upvotes: 0
Views: 926
Reputation: 4656
You have multiple ways of solving your problem :
friends
could be array of names (string)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 |friend_name|
if (friend_name == value)
return "Yes, #{name} is friend with #{friend_name}"
end
end
return "No, #{name} is not friend with #{friend_name}"
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")
addFriend
and first create User
and then add them friends
.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
def addFriend(...)
...
end
end
jane = User.new("Jane", [])
bob = User.new("Bob", [jane])
alice = User.new("Alice", [bob, jane])
bob.isFriendWith("Jane")
jane.isFriendWith("Alice")
alice.isFriendWith("Carlos")
Upvotes: 2