Skip to content

.collect(&:id)的语法问题 #89

@liangchaob

Description

@liangchaob

在研究 Rails 102 的时候,尝试.collect(&:id)的语法结构貌似不认这个语法结构:

2.3.1 :047 > topics = [{id:1, title:"topic1"}, {id:2, title:"topic2"}]
 => [{:id=>1, :title=>"topic1"}, {:id=>2, :title=>"topic2"}]
2.3.1 :048 > topics.collect(&:id)
NoMethodError: undefined method `id' for {:id=>1, :title=>"topic1"}:Hash
    from (irb):48:in `collect'
    from (irb):48
    from /Users/alan/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>'

试过 stackoverflow 中的不含hash的花括号结构是有效的:

2.3.1 :038 >   a = [ "a", "b", "c", "d" ]
 => ["a", "b", "c", "d"]
2.3.1 :039 > a.collect {|x| x + "!" }
 => ["a!", "b!", "c!", "d!"]

是不是ruby语法结构变化又不兼容了呢,array里面套hash后collect方式是怎样的呢?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions