Dinshaw Raje
Dinshaw Raje

Reputation: 963

Show only 3 values in an array in ruby

I have included given code

@students = "All #{section.count}#{section.values}"

output: "All 9['A','B','C','D','E','F','G','H','I']"

But I want show output to be All 9['A','B','C',...]

Please guide me how to solve this. Thanks in advance.

Upvotes: 0

Views: 1302

Answers (4)

Saran
Saran

Reputation: 404

first get all records and store it on @student. and use first() method

@student.first(count)

Upvotes: 0

Venkatesh Dhanasekaran
Venkatesh Dhanasekaran

Reputation: 344

You can use #take method too. Example:

a = [1,2,3,4,5]
a.take(2) # will give as result [1,2]

Hope it will help.

Upvotes: 1

shivam
shivam

Reputation: 16506

You can print first 3 elements of Array and then manipulate the String to include ellipsis. Here:

section.values
# => ["A", "B", "C", "D", "E", "F", "G", "H", "I"]

puts "#{section.values[0..2]}".sub("]",", ...]")
# ["A", "B", "C", ...]

Upvotes: 3

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do this

@students = "All #{section.count}#{(section.count > 3) ? (section.values[0..2] << '...') : section.values}"

Hope that helps!

Upvotes: 0

Related Questions