배열에서 빈 요소를 어떻게 제거합니까? “Pokhara”, “”, “Dharan”, “Butwal”] 배열에서 빈 요소를

다음 배열이 있습니다

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]

배열에서 빈 요소를 제거하고 다음 결과를 원합니다.

cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

compact루프없이 수행 할 수 있는 방법이 있습니까?



답변

이 작업을 수행하는 방법에는 여러 가지가 있습니다. reject

noEmptyCities = cities.reject { |c| c.empty? }

을 사용 reject!하면 cities제자리에서 수정 됩니다. cities무언가를 거부하거나 거부하지 않으면 반환 값으로 반환 됩니다 nil. 조심하지 않으면 문제가 될 수 있습니다 (댓글에서 지적한 ninja08 덕분에).


답변

1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)

=> ["A", "B", "C"]


답변

여기 나를 위해 일하는 것이 있습니다 :

[1, "", 2, "hello", nil].reject(&:blank?)

산출:

[1, 2, "hello"]


답변

내 프로젝트에서는 다음을 사용합니다 delete.

cities.delete("")


답변

이 배열을 정리하고 싶을 때 사용합니다.

["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]

이것은 모든 공백 또는 nil 요소를 제거합니다.


답변

가장 명백한

cities.delete_if(&:blank?)

nil값과 빈 문자열 ( "") 값 이 모두 제거 됩니다.

예를 들면 다음과 같습니다.

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal", nil]

cities.delete_if(&:blank?)
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]


답변

이 시도:

puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]