用 Ruby 中的数组初始化方法

Initialize method with array in Ruby

我是 ruby 的新手,我试图将一个数组放入初始化方法,但它不是那样工作的,那么如何将一个数组放入这个参数?谢谢

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")

您有多种解决问题的方法:

  • 第一个 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 |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 并首先创建 User 然后添加它们 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")