Quel objet .Net correspond à un hachage IronRuby
Question
Je souhaite appeler une méthode C # à partir d'un script IronRuby qui aboutit à un hachage Ruby.J'ai essayé Dictionary mais cela reste tel quel.
public Dictionary<string, string> GetHash()
{
Dictionary<string, string> hash = new Dictionary<string, string>();
hash.Add("a", "1");
hash.Add("b", "2");
return hash;
}
J'aimerais pouvoir l'utiliser dans mon script IronRuby sous forme de hachage
myHash = scopeObj.GetHash()
myHash.each{ |k,v|
print("#{k}=#{v}")
}
Les résultats sont:
[a, 1]=
[b, 2]=
La solution
Cela ne fonctionne pas comme ça puisque les éléments d'un dictionnaire .NET sont des instances KeyValuePair.
Vous pouvez contourner ce problème assez facilement, avec une seule ligne de code de conversion:
d = scopeObj.get_hash
h = Hash[*d.collect { |x| [x.key,x.value] }.flatten]
h.each { |k,v| puts k,v }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow