开发者

Ruby Syntax for calling methods

I'm farily new to the ruby language and I came ac开发者_高级运维ross this line of code:

f.options[:chart][:defaultSeriesType] = "bar"  

Could somebody please explain that one to me? Because doing this:

f.options([:chart][:defaultSeriesType]) = "bar"  

Gives you an error. Thanks in advance!


f.options should be a hash, like so

f.options = {:chart => {}}

Then the command you first wrote will work. So it is not a method call, but actually setting the value of a hash.

Hope this helps.


You are handling with an hash.
When you have doubts like that do f.options.inspect, it will print out the content of the data structure.
I'll let you understand with an example:
Based from the way you wrote, it seems that you are handling an object organized more on less in this way :

f.options = { chart => {defaultSeriesType => "bar"; somethingElse => "bor"}, graph => {attribute1=> "anotherString"} }

So you can query the object by writing: f.options[:graph][:attribute1] or f.options[:chart][:somethingElse] and so on.
I suggest you to spend one minute on http://www.tryruby.org and playing with the hash, you could also take a look here: http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Hashes

Sure it helps


Whenever you have questions like this, open up the console and play with the objects

>f.options.class
=> Hash
>f.options[:chart].class
=> Hash

f.options[:chart] is returning a Hash. So, the line f.options[:chart][:defaultSeriesType] = "bar" is setting the value for a hash with key as 'defaultSeriesType' and value as 'bar'.

And, it's a good practice to use a symbol instead of string for keys, hence the colon at the front - :defaultSeriesType

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜