大括号:[方括号]、(圆括号) & Ruby & 中的 {Curlies}导轨

发布于 2024-09-11 01:46:44 字数 343 浏览 3 评论 0原文

因此,Ruby 对有时使用大括号而不是 REQUIRE 它们的宽松容忍度给我带来了很多困惑,因为我正在尝试学习 Rails,以及何时/何处使用每个大括号以及为什么?

有时参数或值作为 (@user, @comment) 传递,有时它们似乎是 [ :user =>; comment ] 还有一些只是: :action => 'edit'

我正在谈论 [ ]( ){ } 的用法,

规则是什么?有什么技巧可以帮助你记住吗?

So the loose tolerance of Ruby to use braces sometimes and not REQUIRE them has led to alot of confusion for me as I'm trying to learn Rails and when/where to use each and why?

Sometimes parameters or values are passed as (@user, @comment) and other times they seem to be [ :user => comment ] and still others it's just: :action => 'edit'

I'm talking about the us of [ ] vs ( ) vs { }

What ARE the rules? And are there any tricks you have to help you remember?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鹤仙姿 2024-09-18 01:46:44

括号 () 用于对逻辑或数学表达式进行分组,以及对函数调用的参数进行分组,例如:

a = 2 * (3 + 4)
b = (x==y) || (m==n)
Hash.new.send('[]=', :a, :b)

大括号 {} 用于散列文字和块,例如:

h = {1=>2, 2=>3}
h.each {|k,v| puts k+v}

方括号[] 用于数组文字、数组索引和切片以及从哈希中获取,例如:

arr = [1, 2, 3]
two = arr[1]
three = h[2]

为了混淆问题,哈希文字也可以就地用作方法调用的参数,而无需只要是最后一个参数就需要花括号或圆括号(感谢 samuil)。此外,哈希文字可以在方括号中就地使用,以创建包含哈希的单项数组:

puts 1=>2, 3=>4 #=> 1234
[5=>6, 7=>8]    #=> [{5=>6, 7=>8}]

如有疑问,请始终使用括号对项目进行分组,并将哈希值括在大括号中。

Parentheses () are for grouping logical or mathematical expressions and grouping arguments to a function call, e.g.:

a = 2 * (3 + 4)
b = (x==y) || (m==n)
Hash.new.send('[]=', :a, :b)

Curly Braces {} are used for hash literals and blocks, e.g.:

h = {1=>2, 2=>3}
h.each {|k,v| puts k+v}

Square Brackets [] are used for array literals, array indexing and slicing, and fetching from a hash, e.g.:

arr = [1, 2, 3]
two = arr[1]
three = h[2]

To confuse the matter, hash literals can also be used in-place as an argument to a method call without needing the curly braces or parentheses as long as it is the last argument (thanks samuil). Additionally, hash literals can be used in-place in square brackets to create a single-item array containing the hash:

puts 1=>2, 3=>4 #=> 1234
[5=>6, 7=>8]    #=> [{5=>6, 7=>8}]

When in doubt, always use parentheses to group items and wrap your hashes in curly braces.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文