Showing part of an array....

R

Rosina Bignall

Let's say you have an array which might contain:

colors = ["black","white","red","yellow","green"]

And you'd like to see the first three elements with a ... attached to
the end if there are more than 3.

"colors[0,2].join(', ') + ' ...' if colors.count > 3"

Which of course is blank in there are less than 3 elements in the array.

How do I limit the if to only working on the ' ...' part?

Sorry for the newbie question, but I have no idea what to even look for
in the docs.

Thanks!
 
X

xicheng

Rosina said:
Let's say you have an array which might contain:

colors = ["black","white","red","yellow","green"]

And you'd like to see the first three elements with a ... attached to
the end if there are more than 3.

"colors[0,2].join(', ') + ' ...' if colors.count > 3"

Which of course is blank in there are less than 3 elements in the array.

How do I limit the if to only working on the ' ...' part?

def print_color(colors)
if colors.size > 3
puts colors[0,3].join(', ')+' ...'
else
puts colors.join(', ')
end
end
 
D

Daniel Schierbeck

Rosina said:
Let's say you have an array which might contain:

colors = ["black","white","red","yellow","green"]

And you'd like to see the first three elements with a ... attached to
the end if there are more than 3.

"colors[0,2].join(', ') + ' ...' if colors.count > 3"

Which of course is blank in there are less than 3 elements in the array.

How do I limit the if to only working on the ' ...' part?

puts "#{colors[0, 2].join(', ')}#{'...' if colors.length > 3}"
 
R

Rosina Bignall

Daniel said:
Rosina said:
How do I limit the if to only working on the ' ...' part?

puts "#{colors[0, 2].join(', ')}#{'...' if colors.length > 3}"

That's what I thought, but this is actually being passed as an argument
to be evaluated:

@scaffold_columns = [
AjaxScaffold::ScaffoldColumn.new(self, { :name => "colors",
:eval => "#{breed.colors[0, 2].collect{ |color| color.name}.join(',
')}#{'...' if breed.colors.length > 3}",
:sortable => false } )
]

so I am just left with an blank column.

Thanks for your help!
Rosina
 
D

Dumaiu

I think this example is asking for the ternary op.

colors = %w( black red white yellow green )
colors[0,3].join(', ') + (colors.length > 3 ? ' ...' : '')
 
R

Rosina Bignall

Dumaiu said:
I think this example is asking for the ternary op.

colors = %w( black red white yellow green )
colors[0,3].join(', ') + (colors.length > 3 ? ' ...' : '')

Thank you! Thank you! Thank you! Yes, that's exactly what it needs!

Cheers,
Rosina
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,209
Messages
2,571,088
Members
47,686
Latest member
sparada

Latest Threads

Top