Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a literal notation for an array of symbols?

People also ask

What is a literal array?

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

What is the correct syntax for declaring an array literal?

Declaring Arrays:typeName variableName[size]; This declares an array with the specified size, named variableName, of type typeName. The array is indexed from 0 to size-1. The size (in brackets) must be an integer literal or a constant variable.

What is the symbol for an array?

(In essence, the [] is used when declaring a variable of array type, or when indexing into it -- e.g. items[0] or items[items.

Can a string be represented by an array of symbols?

A string can be represented by an array of symbols. Explanation : In C language the string is represented as an array of characters because C language does not support strings as a data type.


Yes! This is possible now in Ruby 2.0.0. One way to write it is:

%i{foo bar}  # => [:foo, :bar]

You can also use other delimiters, so you could also write %i(foo bar) or %i!foo bar! for example.

This feature was originally announced here:

http://www.ruby-lang.org/zh_TW/news/2012/11/02/ruby-2-0-0-preview1-released/

It is mentioned in the official documentation of Ruby here:

http://ruby-doc.org/core/doc/syntax/literals_rdoc.html#label-Percent+Strings


In Ruby 1.x, unfortunately the list of available %-delimiters is limited

Modifier    Meaning
%q[ ]       Non-interpolated String (except for \\ \[ and \])
%Q[ ]       Interpolated String (default)
%r[ ]       Interpolated Regexp (flags can appear after the closing delimiter)
%s[ ]       Non-interpolated Symbol
%w[ ]       Non-interpolated Array of words, separated by whitespace
%W[ ]       Interpolated Array of words, separated by whitespace
%x[ ]       Interpolated shell command