joanx737 - 5 months ago 35

Ruby Question

I'm taking a number of variables in ruby and dividing them by some other constant.

I'm wondering if there's a DRY-er way to write something like the below:

`ela_articles /= ela_active_students.to_f`

ela_days /= ela_active_students.to_f

ela_growth /= ela_active_students.to_f

ela_at_above_now /= ela_active_students.to_f

ela_at_above_before /= ela_active_students.to_f

Answer

If you wish to apply the same method to multiple variables at the same time you can do the following:

```
a = 10
b = 20
c = 5
a, b = [a,b].map { |n| n.fdiv c }
a #=> 2.0
b #=> 4.0
```

Here we're using parallel assignment to redefine the variables `a`

and `b`

. For the division we've used Fixnum#fdiv which divides `n`

by `c`

and returns a float. You can of course use `n/c.to_f`

instead.