gpt4 book ai didi

ruby - 提高大型 attr_accessor 的可读性

转载 作者:太空宇宙 更新时间:2023-11-03 17:55:21 25 4
gpt4 key购买 nike

定义非常大的常量或attr_accessor符号时怎么办?例如,像这样:

ATTRIBUTES = %w(id name full_name owner private html_url description fork url forks_url keys_url collaborators_url teams_url hooks_url issue_events_url events_url assignees_url branches_url tags_url blobs_url git_tags_url git_refs_url trees_url statuses_url languages_url stargazers_url contributors_url subscribers_url subscription_url commits_url git_commits_url comments_url issue_comment_url contents_url compare_url merges_url archive_url downloads_url issues_url pulls_url milestones_url)

attr_accessor :name, :login, :full_name, :owner, :private, :html_url, :description, :fork, :url

在类里面很糟糕。这是最好的方法吗?我想知道是否还有其他方法可以提高可读性。

最佳答案

以一定宽度改变线条:

ATTRIBUTES = %w[
id name full_name owner private html_url description fork url forks_url
keys_url collaborators_url teams_url hooks_url issue_events_url events_url
...
]

或者如果您不需要保存行,那么将每个项目放在单独的行上可能很容易:

ATTRIBUTES = %w[
id name
full_name
owner
private
html_url
...
]

或者如果你有时间格式化,那么你可能想要制作几列并对齐它们:

ATTRIBUTES = %w[
id name full_name owner
private html_url description fork url forks_url
keys_url collaborators_url teams_url hooks_url
issue_events_url events_url ...
]

在 Ruby 2.0 中,为符号数组引入了一个新的文字表达式 %i[...]:

attr_accessor *%i[
name
login
full_name
owner
private
...
]

关于ruby - 提高大型 attr_accessor 的可读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15096300/

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