Access Ruby hash variables

后端 未结 3 721
南旧
南旧 2021-02-01 19:58

I am pretty new to ruby and sinatra but basically I have this route:

put \'/user_list/:user_id\' do
    puts request.params[\"model\"]
end

and

相关标签:
3条回答
  • 2021-02-01 20:01

    Try request.params["model"]["password"]

    A Hash's keys can consist of both symbols and strings. However, a string key is different than a symbol key.

    Note the following:

    h = {:name => 'Charles', "name" => 'Something else'}
    h[:name] #=> 'Charles'
    h["name"] #=> 'Something else'
    

    EDIT:

    In your particular situation, it appears request.params["model"] returns a string instead of a hash. There is a method String#[] which is a means of getting a substring.

    s = "Winter is coming"
    s["Winter"] #=> "Winter"
    s["Summer"] #=> nil
    

    This would explain your comments.

    There are a couple things you can do to remedy your specific situation. I have found the most simplest way to be using JSON. (I'm sure there are others and maybe those will surface through other answers or through comments.)

    require 'json'
    hash_of_params = JSON.load(request.params["model"]).to_hash
    hash_of_params["password"] #=> "36494092d7d5682666ac04f62d624141"
    
    0 讨论(0)
  • 2021-02-01 20:11

    The standard Hash treats strings and symbols differently, and I'd be willing to bet that's what's happening in this case.

    Use request.params["model"]["password"] to get the password.

    The exception to that is when working with a HashWithIndifferentAccess which is part of ActiveSupport. For hashes of that type, either strings or symbols can be used to access the same elements.

    0 讨论(0)
  • 2021-02-01 20:19

    Try the below,it will work too:

    request.params["model"][:password.to_s]
    
    0 讨论(0)
提交回复
热议问题