Are there ruby equivalents to car, cdr, and cons?

前端 未结 5 940
终归单人心
终归单人心 2021-02-05 05:35

Are there ruby equivalents to the lisp car, cdr, and cons functions? For those unfamiliar with lisp, here\'s what I want from ruby:

[1,2,3].car   => 1
[1,2,3]         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 06:32

    Ruby arrays are not implemented as singly-linked lists, so it is not as useful to have car and cdr and stuff.

    If you really wanted, you could do

    [1,2,3][0]      => 1
    [1,2,3].first   => 1
    [1,2,3][1..-1]  => [2,3]
    [1] + [2,3]     => [1,2,3]
    

提交回复
热议问题