Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

ruby extract elements from array

Suppose you have an array of hashes like this:

```ruby
arr = [{a: 1, b: 2}, {c: 3, d: 4}, {e: 5, f: 6}]
```

You can extract the values corresponding to a given key like this:

```ruby
arr.map { |h| h[:a] }
# => [1, nil, nil]
```

```ruby
arr.map { |h| h[:b] }
# => [2, nil, nil]
```

```ruby
arr.map { |h| h[:c] }
# => [nil, 3, nil]
```

```ruby
arr.map { |h| h[:d] }
# => [nil, 4, nil]
```

```ruby
arr.map { |h| h[:e] }
# => [nil, nil, 5]
```

```ruby
arr.map { |h| h[:f] }
# => [nil, nil, 6]
```

If you want to get all the values for all the keys, you can use `#values`:

```ruby
arr.map { |h| h.values }
# => [[1, 2], [3, 4], [5, 6]]
```
Comment

PREVIOUS NEXT
Code Example
Ruby :: ruby &w 
Ruby :: rails callback STI 
Ruby :: ruby check if string is integer 
Ruby :: ruby on rails project 
Ruby :: ruby-on-rails 
R :: convert latin accents to ascii R 
R :: r ggplot regression line 
R :: ggplot increase label font size 
R :: WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding: 
R :: collapse text by group in dataframe r 
R :: how to transform days in years R 
R :: merge several data frames in r 
R :: name elements in vector r 
R :: create a dataframe with column names in r 
R :: how to create dictionary in R 
R :: null count in r 
R :: delete all rows that contain a string in R 
R :: convert na to 0 in r 
R :: r extract top values from data frame 
R :: How to extract the row with min or max values? in R 
R :: how to use r with variable 
R :: insert character into string 
R :: R: foreach multiple argument 
R :: r code mutate 
R :: print string without quotes and escape sequence r 
R :: base R change axis line width 
R :: get string without ending in R 
Rust :: rust print array 
Rust :: rust simple search and replace regex 
Rust :: read line rust 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =