Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a comma followed by an equals sign mean in Ruby?

Tags:

ruby

Just saw something like this in some Ruby code:

def getis;gets.split.map(&:to_i);end

k,=getis # What is this line doing?
di=Array::new(k){Array::new(k)}
like image 222
Siu Chung Chan Avatar asked Nov 21 '14 09:11

Siu Chung Chan


People also ask

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What does %I mean in Ruby?

The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.


1 Answers

It assigns the array's first element using Ruby's multiple assignment:

a, = [1, 2, 3]
a #=> 1

Or:

a, b = [1, 2, 3]
a #=> 1
b #=> 2

You can use * to fetch the remaining elements:

a, *b = [1, 2, 3]
a #=> 1
b #=> [2, 3]

Or:

*a, b = [1, 2, 3]
a #=> [1, 2]
b #=> 3
like image 130
Stefan Avatar answered Oct 12 '22 10:10

Stefan