Qrious
Qrious

Reputation: 5

Print Array in Ruby with Multiplication

I'm trying to wrap my head around Ruby and was wondering if anyone on here could help me with my problem.

I want an array that goes up to 5.

arr = [1, 2, 3, 4, 5]

Then I want it to print that array and also include it in an equation, of sorts.

So, something like this:

puts (56 * arr) + (30 * (arr-1)) =>

56
142
228
314
400

Essentially, I want to further print something like so:

puts ".col-"arr" { " (56 * arr) + (30 * (arr-1)) "px };"

So it prints something like this:

.col-1 { 56px; }
...

Is this possible using Ruby?

Upvotes: 0

Views: 100

Answers (2)

Jokester
Jokester

Reputation: 5617

The per-element computation is easy with Array#map or Array#each.

> arr = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
> arr.map{|elem| 56*elem + 30*(elem-1)}
=> [56, 142, 228, 314, 400]
> arr.each{|elem| puts ".col-#{elem} { #{56*elem + 30*(elem-1)} px };" }
=> the CSS

Upvotes: 1

Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 18567

arr.each { |n| puts ".col-#{n} { #{56*n + 30*(n-1)}px; }" }

Upvotes: 0

Related Questions