What do the different brackets in Ruby mean?

前端 未结 6 2080
萌比男神i
萌比男神i 2020-12-04 16:40

In Ruby, what\'s the difference between {} and []?

{} seems to be used for both code blocks and hashes.

Are []

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 17:13

    The square brackets [ ] are used to initialize arrays. The documentation for initializer case of [ ] is in

    ri Array::[]
    

    The curly brackets { } are used to initialize hashes. The documentation for initializer case of { } is in

    ri Hash::[]
    

    The square brackets are also commonly used as a method in many core ruby classes, like Array, Hash, String, and others.

    You can access a list of all classes that have method "[ ]" defined with

    ri []
    

    most methods also have a "[ ]=" method that allows to assign things, for example:

    s = "hello world"
    s[2]     # => 108 is ascii for e
    s[2]=109 # 109 is ascii for m
    s        # => "hemlo world"
    

    Curly brackets can also be used instead of "do ... end" on blocks, as "{ ... }".

    Another case where you can see square brackets or curly brackets used - is in the special initializers where any symbol can be used, like:

    %w{ hello world } # => ["hello","world"]
    %w[ hello world ] # => ["hello","world"]
    %r{ hello world } # => / hello world /
    %r[ hello world ] # => / hello world /
    %q{ hello world } # => "hello world"
    %q[ hello world ] # => "hello world"
    %q| hello world | # => "hello world"
    

提交回复
热议问题