为了提高我的Rails
应用安全性,我想知道如何从参数哈希中获取所有键
哈希示例:
params =
{"id"=>23, "name"=>"test", "infos"=>{"data"=>"er323e3ee23reQir", "signed"=>true}}
如果我params.keys
我获得了:["id", "name", "infos"]
但我希望以简单的数组获取所有密钥,例如:["id", "name", "infos", "data", "signed"]
有一种简单的方法可以做到这一点吗?
答案 0 :(得分:3)
试试这个:
def deep_hash_keys(h)
h.keys + h.map { |_, v| v.is_a?(Hash) ? deep_hash_keys(v) : nil }.flatten.compact
end
params = {"id"=>23, "name"=>"test", "infos"=>{"data"=>"er323e3ee23reQir", "signed"=>true}}
deep_hash_keys(params) # => ["id", "name", "infos", "data", "signed"]
答案 1 :(得分:0)
我会使用一种新方法:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class PlayerStats : NetworkBehaviour
{
NetworkConfigurator netConf;
[SyncVar]
public float playerHealth;
void Start ()
{
netConf = GameObject.Find ("NetworkManager").GetComponent<NetworkConfigurator> ();
netConf.userStatus.SetActive (isLocalPlayer); // Here the problem
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.LeftBracket))
{
if (playerHealth == 0)
return;
playerHealth -= 5;
}
if (Input.GetKeyDown (KeyCode.RightBracket))
{
if (playerHealth == 100)
return;
playerHealth += 5;
}
netConf.healthAmount.text = "" + playerHealth;
netConf.healthBar.fillAmount = playerHealth / 100;
}
}
优点:您还可以在非哈希函数中定义all_keys方法。
答案 2 :(得分:0)
你可以修补哈希类:
class Hash
def all_keys
keys + map { |k, v| v.is_a?(Hash) ? v.all_keys : nil }.flatten.compact
end
end
params = {"id"=>23, "name"=>"test", "infos"=>{"data"=>"er323e3ee23reQir", "signed"=>true}}
params.all_keys # => ["id", "name", "infos", "data", "signed"]