Home > Enterprise >  Condition in ruby on rails - if else
Condition in ruby on rails - if else

Time:12-16

I'm not really sure what this means. This is from Ruby on Rails in controller class and been trying to figure out what the below code do.

payload = if params.key? :data
            //do something
          else 
            //else do something
          end

This is in the controller class. What does the params.key? :data do?

The data variable doesn't exist in the whole class but just in this block.

CodePudding user response:

:data is not a variable but a symbol.

.key? is a method and in ruby you do not need parentheses to pass a parameter such as :data.

So this bit of code asks if params has the symbol :data as a key (in a map) and uses the returning boolean for the conditional.

CodePudding user response:

In this snippet data is not a variable, it is a symbol literal. Java doesn't have a direct counterpart of Ruby's symbols AFAIR, but you can think of it as of some immutable identifier (kinda "immutable string with some additional cool properties that don't matter in the context we discuss here").

Next, params represents query params and is provided by the underlying middleware. It is a Hash-like data structure where Hash is a Ruby's counterpart of Java's HashMap that maps keys to values.

Next, params.key? :data is the same as params.key?(:data) - parentheses around method's arguments are optional in Ruby in most cases, and people tend to abuse this controversial feature. It just checks if params hash(map) contains a :data key (see Hash#key?).

And finally since everything in Ruby is an expression, if... else... end has a meaningful return value (the result of the particular branch execution) that is further assigned to the payload.

  • Related