Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this Ruby syntax?

Tags:

ruby

I recently ran into code that looks like this:

 next {
          'foo'         => bar,
          'foobar'      => anotherbar,
      }

At first it looks like a simple hash, but there is no assignment to next. Next in this case looks like a reserved Ruby keyword. What does this code do?

like image 380
randombits Avatar asked Jul 20 '10 03:07

randombits


People also ask

What syntax does Ruby use?

The syntax of the Ruby programming language is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords, whereas code blocks can be defined by either keywords or braces. In contrast to Perl, variables are not obligatorily prefixed with a sigil.

What is :: in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.

What is an identifier in Ruby?

Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby. Ruby identifier names may consist of alphanumeric characters and the underscore character ( _ ).

What is Symbol in Ruby?

What's a Symbol in Ruby? A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource. A resource can be: a method.


1 Answers

next is similar to the continue keyword in the c family of languages, except in ruby it makes an iterator move to the next iteration. Since blocks always have some sort of return value you can choose to pass one as an argument to next.

next is typically used in cases like iterating through a list of files and taking action (or not) depending on the filename.

next can take a value, which will be the value returned for the current iteration of the block.

  sizes = [0,1,2,3,4].map do |n|
    next("big") if n > 2
    puts "Small number detected!"
    "small"
  end

  p sizes

Output:

  Small number detected!
  Small number detected!
  Small number detected!
  ["small", "small", "small", "big", "big"]

from http://ruby-doc.org/docs/keywords/1.9/

like image 165
cris.h Avatar answered Sep 22 '22 07:09

cris.h