gpt4 book ai didi

ruby - << sign bypass = sign in ruby​​ 吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:46:29 26 4
gpt4 key购买 nike

class Book
attr_accessor :author
attr_reader :title
attr_reader :comments
def initialize(author, title)
@author = author
@title = title
@comments = []
end
end

book = Book.new("Chuck Palahniuk", "Fight Club")


book.comments << "#{book.title} was a good book"
book.comments.each do |p|
puts p
end
# Fight Club was a good book

如果 comments 方法只是一个 attr_reader 而不是 attr_writer,为什么 << appending 起作用?是因为它绕过了 = 符号,也就是 attr_writer 吗?

最佳答案

带有<<的声明修改 book.comments 的数组引用,它不会改变book.comments本身。

打印其 object_id之前和之后:

puts book.comments.object_id
book.comments << "#{book.title} was a good book"
puts book.comments.object_id

您会看到它是同一个对象。


与非法语句对比:

book.comments = []

关于ruby - << sign bypass = sign in ruby​​ 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26954478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com