Ruby 루프의 첫 번째 반복에서 다르게 작동하는 방법은 무엇입니까?
나는 항상 카운터를 사용 i==0
하여 루프 의 첫 번째 항목 ( ) 을 확인 합니다.
i = 0
my_array.each do |item|
if i==0
# do something with the first item
end
# common stuff
i += 1
end
이를 수행하는 더 우아한 방법이 있습니까 (아마도 방법)?
다음과 같이 할 수 있습니다.
my_array.each_with_index do |item, index|
if index == 0
# do something with the first item
end
# common stuff
end
ideone에서 시도해보십시오 .
each_with_index
다른 사람들이 설명했듯이를 사용하면 잘 작동하지만 여기서 다양성을 위해 또 다른 접근 방식이 있습니다.
첫 번째 요소에만 특정한 작업을하고 첫 번째 요소를 포함한 모든 요소에 대해 일반적인 작업을 수행하려면 다음을 수행 할 수 있습니다.
# do something with my_array[0] or my_array.first
my_array.each do |e|
# do the same general thing to all elements
end
그러나 첫 번째 요소로 일반적인 작업을 수행하지 않으려면 다음을 수행 할 수 있습니다.
# do something with my_array[0] or my_array.first
my_array.drop(1).each do |e|
# do the same general thing to all elements except the first
end
배열에는이 상황에 편리한 "each_with_index"메소드가 있습니다.
my_array.each_with_index do |item, i|
item.do_something if i==0
#common stuff
end
가장 적합한 것은 상황에 따라 다릅니다.
다른 옵션 (배열이 비어 있지 않은 경우) :
# treat the first element (my_array.first)
my_array.each do | item |
# do the common_stuff
end
each_with_index
에서 Enumerable에서 (당신은 아무 문제없이 배열에 호출 할 수 있도록 Enumerable에서 이미 배열에 혼합) :
irb(main):001:0> nums = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):003:0> nums.each_with_index do |num, idx|
irb(main):004:1* if idx == 0
irb(main):005:2> puts "At index #{idx}, the number is #{num}."
irb(main):006:2> end
irb(main):007:1> end
At index 0, the number is 1.
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
나중에 어레이가 필요하지 않은 경우 :
ar = %w(reversed hello world)
puts ar.shift.upcase
ar.each{|item| puts item.reverse}
#=>REVERSED
#=>olleh
#=>dlrow
루비 Enumerable#inject
는 루프의 첫 번째 반복에서 다른 작업을 수행하는 데 사용할 수있는 인수를 제공합니다.
> l=[1,2,3,4]
=> [1, 2, 3, 4]
> l.inject(0) {|sum, elem| sum+elem}
=> 10
이 인수는 합계 및 제품과 같은 일반적인 항목에 엄격하게 필요하지 않습니다.
> l.inject {|sum, elem| sum+elem}
=> 10
그러나 첫 번째 반복에서 다른 작업을 수행하려는 경우 해당 인수가 유용 할 수 있습니다.
> puts fruits.inject("I like to eat: ") {|acc, elem| acc << elem << " "}
I like to eat: apples pears peaches plums oranges
=> nil
다음은 즉시 둘러싸는 루프에있을 필요가없고 실제로 필요하지 않는 한 상태 자리 표시자를 두 번 이상 지정하는 중복을 피하는 솔루션입니다.
do_this if ($first_time_only ||= [true]).shift
Its scope matches the holder: $first_time_only
will be globally once; @first_time_only
will be once for the instance, and first_time_only
will be once for the current scope.
If you want the first several times, etc, you can easily put [1,2,3]
if you need to distinguish which of the first iterations you're in, or even something fancy [1, false, 3, 4]
if you need something weird.
참고URL : https://stackoverflow.com/questions/8181390/how-to-act-differently-on-first-iteration-in-a-ruby-loop
'Development Tip' 카테고리의 다른 글
Java 프로그램을 데몬 화하는 방법? (0) | 2020.10.29 |
---|---|
sql, A 열로 정렬 한 다음 B 열로 정렬 (0) | 2020.10.29 |
WCF에서 메서드 오버로딩이 허용되지 않는 이유는 무엇입니까? (0) | 2020.10.29 |
문자열 매개 변수를 허용하는 생성자로 클래스 객체를 인스턴스화 하시겠습니까? (0) | 2020.10.29 |
자바 제네릭 슈퍼 키워드 (0) | 2020.10.29 |