Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`map` based on condition

Tags:

ruby

struct

I have a struct like this:

Struct.new("Test", :loc, :type, :hostname, :ip)

clients = [
Struct::TestClient.new(1, :pc, "pc1", "192.168.0.1")
Struct::TestClient.new(1, :pc, "pc2", "192.168.0.2")
Struct::TestClient.new(1, :tablet, "tablet1", "192.168.0.3")
Struct::TestClient.new(1, :tablet, "tablet2", "192.168.0.3")
and etc...
]

If I want to get the IP address of all devices, I can use test_clients.map(&:ip). How do I select the IP addresses of specific devices, say all device types called "tablet"? How can I do that with map?

like image 473
sylvian Avatar asked Mar 16 '13 00:03

sylvian


People also ask

How do you use condition on a map?

To use a condition inside map() in React:Call the map() method on an array. Use a ternary operator to check if the condition is truthy. The operator returns the value to the left of the colon if the condition is truthy, otherwise the value to the right is returned.

How do you use the map function in react?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.

How do you conditionally render multiple components in react?

We used a ternary operator to conditionally render multiple elements. The ternary operator is very similar to an if/else statement. If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned. Copied!


1 Answers

Do a select first

clients.select{|c| c.type == 'tablet'}.map(&:ip)
like image 154
Sergio Tulentsev Avatar answered Oct 06 '22 20:10

Sergio Tulentsev