0

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.

3
  • there's no variable data in this snippet. Commented Dec 15, 2022 at 16:04
  • 2
    "What does the params.key? :data do" - it calls method key? on object params and passes a symbol :data as an argument. Commented Dec 15, 2022 at 16:05
  • 1
    Might be easier to recognize with parentheses: params.key?(:data) Commented Dec 15, 2022 at 16:18

2 Answers 2

4

: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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.