Rztprog
Rztprog

Reputation: 13

Initialize method with array in Ruby

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

Answers (1)

BTL
BTL

Reputation: 4656

You have multiple ways of solving your problem :

  • First 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")
  • Other way is to pass object as you did but in this case you can only pass object already instanciated. In this second choice you can add a method 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

Related Questions