geekelo / geekelo/dsa_practice

How do you remove nil values in array using Ruby?

Open
#5 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
1
Forks
0
PR merge metrics
No merged PRs in 30d

Description

You can remove `nil` values from an array in Ruby using various methods. Here are a few approaches:

1. **Using `compact` method:**
The `compact` method removes `nil` values from an array.

```ruby
my_array = [1, 2, nil, 3, nil, 4]
result_array = my_array.compact
```

After this, `result_array` will contain `[1, 2, 3, 4]`.

2. **Using `reject` method:**
The `reject` method can be used to exclude elements that meet a certain condition, and you can use it to exclude `nil` values.

```ruby
my_array = [1, 2, nil, 3, nil, 4]
result_array = my_array.reject { |item| item.nil? }
```

After this, `result_array` will also contain `[1, 2, 3, 4]`.

3. **Using `compact!` method (modifies the original array):**
The `compact!` method removes `nil` values from the array in place.

```ruby
my_array = [1, 2, nil, 3, nil, 4]
my_array.compact!
```

After this, `my_array` will be `[1, 2, 3, 4]`.

Choose the method that best fits your use case. If you want to keep the original array unchanged, use `compact` or `reject` to create a new array without modifying the original one. If you don't mind modifying the original array, you can use `compact!`.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.