2012-11-14 3 views
4

나는 예를 들어, 단지 얼랑을 배우기 시작, 정말 자신의 지능형리스트 구문 같은 :얼랑 루비 대 지능형리스트

이 경우
Weather = [{toronto, rain}, {montreal, storms}, {london, fog}, {paris, sun}, {boston, fog}, {vancounver, snow}].       
FoggyPlaces = [X || {X, fog} <- Weather]. 

, FoggyPlaces이 "런던"와 "보스턴"평가합니다.

Ruby에서 가장 좋은 방법은 무엇입니까? 예를 들어

, (나는 매우 일반적인 생각)와 같은 배열 :

weather = [{city: 'toronto', weather: :rain}, {city: 'montreal', weather: :storms}, {city: 'london', weather: :fog}, {city: 'paris', weather: :sun}, {city: 'boston', weather: :fog}, {city: 'vancounver', weather: :snow}] 

지금은 '때까지 가지고 최선은 다음과 같습니다

weather.collect {|w| w[:city] if w[:weather] == :fog }.compact 

그러나이 경우

, 내가 전화를해야 compact을 사용하여 nil 값을 제거하십시오. 예제 자체는 Erlang만큼 읽을 수 없습니다.

얼랭 예제에서 cityweather은 모두 원자입니다. 나는 루비에서 뭔가 의미있는 것을 얻고 이것처럼 보이는 것을 얻는 방법조차 모른다.

+0

FAQ입니다. http://stackoverflow.com/questions/11319429/does-ruby-have-something-like-pythons-list-comprehensionsexample, http://stackoverflow.com/questions/310426/list-comprehension -in-ruby, http://stackoverflow.com/questions/9737525/list-comprehension-in-haskell-python-and-ruby. – tokland

+1

erlang은 매우 선언적이며 상징적입니다. 인간과 매우 가깝습니다. –

답변

10

먼저 데이터 구조가 동일하지 않습니다. 당신의 얼랑 예에 해당하는 루비 데이터 구조는

weather = [[:toronto, :rain], [:montreal, :storms], [:london, :fog], 
      [:paris, :sun], [:boston, :fog], [:vancouver, :snow]] 

이 두 번째로, 그래, 루비는 지능형리스트도 패턴 매칭이없는 이상과 같은 것입니다. 따라서 예제 이 더 복잡 할 것입니다. 목록 이해력은 처음에는 모든 안개가 자욱한 도시를 필터링 한 다음 이름을 투사합니다. 의 루비에서 동일한 작업을 수행하자

그러나
weather.select {|_, weather| weather == :fog }.map(&:first) 
# => [:london, :boston] 

, 루비는 객체 중심으로,하지만 당신은 추상 데이터 타입을 사용하고 있습니다. 더 객체 지향 데이터 추상화로, 코드는 아마, 나쁘지 않네요 그것이

weather.select(&:foggy?).map(&:city) 

과 같을 것이다?

+0

얼랑 튜플은 루비 해시와 동일하지 않습니까? – caarlos0

+1

오브젝트에 대한 +1 비트. 직접 번역은 일반적으로 관용적 인 번역이 아닙니다. –

+1

아니요, Erlang'dict'는 Ruby'Hash'es와 같습니다. 루비에는 튜플과 직접적인 동일한 기능이 없습니다. 가장 가까운 것은 배열입니다. –