development

Ruby 배열의 마지막 요소를 제외한 모든 요소

big-blog 2020. 7. 2. 07:17
반응형

Ruby 배열의 마지막 요소를 제외한 모든 요소


루비 배열이 있다고 가정 해 봅시다.

a = [1, 2, 3, 4]

첫 번째 항목을 제외한 모든 것을 원하면 쓸 수 있습니다 a.drop(1). 그래도 마지막 항목을 제외한 모든 것을 원한다면 이 방법 만 생각할 수 있습니다

a[0..-2]   # or
a[0...-1]

그러나 이것들 중 어느 것도 사용하는 것만 큼 깨끗한 것처럼 보이지 않습니다 drop. 내가 놓친 다른 내장 방법은 무엇입니까?


혹시...

a = t               # => [1, 2, 3, 4]
a.first a.size - 1  # => [1, 2, 3]

또는

a.take 3

또는

a.first 3

또는

a.pop

마지막을 반환하고 배열 앞에 모든 것을 남겨 둡니다.

또는 저녁 식사를 위해 컴퓨터를 작동 시키십시오 .

a.reverse.drop(1).reverse

또는

class Array
  def clip n=1
    take size - n
  end
end
a          # => [1, 2, 3, 4]
a.clip     # => [1, 2, 3]
a = a + a  # => [1, 2, 3, 4, 1, 2, 3, 4]
a.clip 2   # => [1, 2, 3, 4, 1, 2]

호기심에서, 당신은 왜 안 좋아 a[0...-1]합니까? 배열 조각을 얻으려고하므로 조각 연산자는 관용적 인 선택처럼 보입니다.

그러나 이것을 모든 곳에서 호출 해야하는 경우 DigitalRoss가 제안한 것처럼 항상 더 친숙한 이름의 메소드를 Array 클래스에 추가 할 수 있습니다. 아마도 이것처럼 :

class Array
    def drop_last
        self[0...-1]
    end
end

또 다른 멋진 트릭

>> *a, b = [1,2,3]
=> [1, 2, 3]
>> a
=> [1, 2]
>> b
=> 3

pop()배열 에서 작업 을 수행 하려고하지만 (마지막 항목이 삭제 될 수 있음) 팝업 요소 대신 배열을 얻는 데 관심이있는 경우 다음을 사용할 수 있습니다 tap(&:pop).

> arr = [1, 2, 3, 4, 5]
> arr.pop
=> 5
> arr
=> [1, 2, 3, 4]
> arr.tap(&:pop)
=> [1, 2, 3]

나는 이렇게한다 :

my_array[0..-2]

예를 들어 드롭 방법 자체를 보강하는 것은 어떻습니까?

class Array
  def drop(n)
    n < 0 ? self[0...n] : super
  end
end

그런 다음 음수 크기를 사용하여 끝에서 요소를 제거 할 수 있습니다.

[1, 2, 3, 4].drop(-1) #=> [1, 2, 3]
[1, 2, 3, 4].drop(-2) #=> [1, 2]

a[0...-1]가장 좋은 방법 같습니다. 배열 슬라이싱 구문은 정확히이 목적으로 만들어졌습니다 ...

또는 배열을 수정하는 것이 마음에 들지 않으면 a.pop다음을 호출하면됩니다 .

>> a = [1, 2, 3, 4]
>> a.pop
>> a
=> [1, 2, 3]

이게 방법이야:

[1,2,3,4,5][0..-1-1]

그러나 이것이 어떻게 작동하는지 설명합시다.

a = [1,2,3,4,5]

다음 예제는 0 위치에서 마지막 위치까지 모든 레코드를 반환합니다.

a[0..-1]
=> [1, 2, 3, 4, 5]

다음 예제는 1 위치에서 마지막 레코드 반환합니다.

a[1..-1]
=> [2, 3, 4, 5]

And here you have what you need. Next example will return records from 0 position to last-1

a[0..-1-1]
=> [1, 2, 3, 4]

To get rid of the last element in one line with the remainder returning

[1, 2, 4, 5, 6].reverse.drop(1).reverse

Seriously though,

[1,2,3,4][0..-2]
#=> [1,2,3]

Have you tried "take"

a.take(3) 

Answer: a.τwτ, but you have to install Pyper first...

Pyper intro: Do you know Lispy car and cdr returning "first" and "rest" of the array? Just for the needs like yours, I made an extension of this Lispy mechanism. It's called pyper, and it allows you to access also 2nd, rest from 2nd, 3rd, rest from 3d, and also last, everything except last etc. That wouldn't be much to write about, but it also allows letter composition, just like caar, cadr, cdadar etc. known from Lisp:

# First, gem install pyper
require 'pyper'
include Pyper
a = %w/lorem ipsum dolor sit amet/
# To avoid confusion with other methods, and also because it resembles a rain gutter,
# Greek letter τ is used to delimit Pyper methods:
a.τaτ #=> "lorem"
a.τdτ #=> ["ipsum", "dolor", "sit", "amet"]
a.τbτ #=> "ipsum"
a.τeτ #=> ["dolor", "sit", "amet"]
a.τcτ #=> "dolor" (3rd)
a.τzτ #=> "amet" (last)
a.τyτ #=> "sit" (2nd from the end)
a.τxτ #=> "dolor" (3rd from the end)

and finally, the answer to your question:

a.τwτ #=> ["lorem", "ipsum", "dolor", "sit"] (all except last)

There is more:

a.τuτ #=> ["lorem", "ipsum", "dolor"] (all except last 2)
a.τ1τ #=> ["lorem", "ipsum"] (first 2)
a.τ8τ #=> (last 2)
a.τ7τ #=> (last 3)

Compositions:

a.τwydτ #=> "olor" (all except 1st letter of the last word of all-except-last array)

There are also more command characters than just a..f, u..z and 0..9, most notably m, meaning map:

a.τwmbτ #=> ["o", "p", "o", "i"] (second letters of all-except-last array)

But other command characters are too hot and not very easy to use at the moment.


This makes a new array with all but the last elements of the original:

ary2 = ary.dup
ary2.pop

Note that a few others have suggested using #pop. If you are ok modifying the array in place, that's fine. If you aren't ok with that, then dup the array first, as in this example.


I often find myself wanting all but the last n elements of an array. I've rigged up my own function to do this in a way that I find more readable than other solutions:

class Array
  def all_but_the_last(n)
    self.first(self.size - n)
  end
end

Now you can do the following:

arr = ["One", "Two", "Three", "Four", "Five"]
# => ["One", "Two", "Three", "Four", "Five"]

arr.all_but_the_last(1)
# => ["One", "Two", "Three", "Four"]

arr.all_but_the_last(3)
# => ["One", "Two"]

arr.all_but_the_last(5)
# => []

arr.all_but_the_last(6)
# ArgumentError: negative array size

I've deliberately allowed for the ArgumentError so that the caller is responsible for how they use this method. I'd love to hear comments/criticisms of this approach.


a = [1,2,3,4]

a[0..(a.length - 2)]
=> [1,2,3]

참고URL : https://stackoverflow.com/questions/1604305/all-but-last-element-of-ruby-array

반응형