Access Ruby hash variables

后端 未结 3 723
南旧
南旧 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条回答
  •  梦毁少年i
    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"
    

提交回复
热议问题