Ruby/Rails 哈希火箭语法 [英] Ruby/Rails hash rockets Syntax

查看:51
本文介绍了Ruby/Rails 哈希火箭语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能给我推荐一本解释 Ruby/Rails 不同句法特性的入门读物吗?例如,为什么我看到的一些例子是 myMethod(x: "z") 而其他例子是 myMethod(:x => "x")?

Can someone point me to a good primer just explaining the different syntactic features in Ruby/Rails? For instance, how come some examples I see do myMethod(x: "z") and others do myMethod(:x => "x")?

一般的语法对我来说似乎很奇怪,只是寻找一个快速的一目了然的参考以用作备忘单.

The syntax in general seems strange to me, just looking for a quick at-a-glance reference to use as a cheat sheet.

推荐答案

它们是一样的,只是喜好问题.

我还问自己如果我们已经有了这种新语法,为什么还要添加这种新语法?嗯,使用 Ruby 编程意味着我们很懒惰,想要键入不太可能的字符.所以这个新语法允许我们——懒惰的程序员——写同样的东西,减去 1 个字符!

I also asked myself why would we add this new syntax if we already have one? Well, Programming with Ruby implies that we are lazy and want to type the less possible caracters. So this new syntax allow us - lazy programmers - to write the same thing, minus 1 caracter!

但请记住一些东西,例如键的类型(Ruby 1.9.3):

But keep in mind some stuff, like the type of the keys for instance (Ruby 1.9.3):

> {a: 12}.class
 => Hash 
> {:a => 12}.class
 => Hash 
> {'a' => 12}.keys.first.class
 => String 
> {a: 12}.keys.first.class
 => Symbol

另外,一些声明在新语法中是非法的:

Also, some declaration are illegal with the new syntax:

> { '1-2' => "something" }
 => {"1-2"=>"something"} 
> { 1-2: "something" }
SyntaxError: (irb):38: syntax error, unexpected ':', expecting tASSOC
{ 1-2: "something" }
      ^
(irb):38: syntax error, unexpected '}', expecting $end

欲了解更多信息:`:key => 之间有什么区别吗?值"和键:"值哈希符号?

这篇关于Ruby/Rails 哈希火箭语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆