Understanding Erlang vs Ruby List

I just started learning Erlang and really love their list comprehension syntax, for example:

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

In this case, FoggyPlaces will be rated as "London" and "Boston."

What is the best way to do this in Ruby?

For example, an array like (very common, I believe):

  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}] 

The best I've got so far:

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

But in this case, I need to call compact to remove the nil values, and the example itself does not read like Erlang.

And even more, in the example of Erlang, both city and weather are atoms. I don’t even know how to get something that makes sense and looks like in Ruby.

+4
source share
1 answer

First, your data structures are not equivalent. The equivalent Ruby data structure for your Erlang example will be more like

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

Secondly, yes, Ruby does not have lists and pattern matching. Thus, the example is likely to be more complex. Your understanding of the list first filters all the foggy cities, and then designs the name. Do the same in Ruby:

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

However, Ruby is centered around objects, but you are using abstract data types. With a more object-oriented data abstraction, the code is likely to be more like

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

which is not so bad, is it?

+10
source

Source: https://habr.com/ru/post/1445990/


All Articles