开发者

How do dictionary lookups work in IronRuby?

开发者 https://www.devze.com 2023-01-08 15:05 出处:网络
I have this line of IronPython code: Traits[\'Strength\'].Score + Traits[\'Dexterity\'].Score Traits is defined as such:

I have this line of IronPython code:

Traits['Strength'].Score + Traits['Dexterity'].Score

Traits is defined as such:

Dim m_Traits As New Dictionary(Of String, Trait)
scope.SetVariable("Traits", m_Traits)

I would like t开发者_运维技巧o translate the IronPython code into IronRuby, but I'm having trouble finding the correct syntax.


In Ruby (and IronRuby), variables must begin with a lowercase letter. Therefore, just change the Traits variable to traits to make your code works:

var engine = IronRuby.Ruby.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("traits", traits);

dynamic result = engine.Execute("traits['Strength'].Score + traits['Dexterity'].Score", scope);

(this code works, I checked).

By the way, creating a variable that starts with a capital letter makes it a constant (that's how Ruby works) and adding a constant to the scope is done in a slightly different way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号