Ruby:冒号之前与之后 [英] Ruby: colon before vs after

查看:39
本文介绍了Ruby:冒号之前与之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Ruby 时,我总是与 : 混淆.

When using Ruby, I keep getting mixed up with the :.

谁能解释一下我什么时候应该在变量名之前使用它,比如 :name,什么时候我应该在变量之后使用它,比如 name:?

Can someone please explain when I'm supposed to use it before the variable name, like :name, and when I'm supposed to use it after the variable like name:?

举个例子就好了.

推荐答案

在创建 Hash 时,欢迎您使用两者:

You are welcome for both, while creating Hash :

{:name => "foo"}
#or
{name: 'foo'} # This is allowed since Ruby 1.9

但基本上 :name 是一个 Symbol Ruby 中的对象.

But basically :name is a Symbol object in Ruby.

来自文档

当您的键总是符号时,哈希允许替代语法形式.而不是

Hashes allow an alternate syntax form when your keys are always symbols. Instead of

options = { :font_size => 10, :font_family => "Arial" }

你可以写成:

options = { font_size: 10, font_family: "Arial" }

这篇关于Ruby:冒号之前与之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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