13

Is there some method in coffeescript that returns true when an array has some items in it? Like method in ruby present?:

[].present? false
[1].present? true

According to http://arcturo.github.com/library/coffeescript/07_the_bad_parts.html an array emptiness in coffeescript is determined by its length

alert("Empty Array")  unless [].length

that seems so lame to me.

3 Answers 3

23

I don't think there is but can be:

Array::present = ->
  @.length > 0

if [42].present()
  # why yes of course
else
  # oh noes

A very simple and incomplete implementation but it should give you some ideas. And for the record, there's no present? method in Ruby, the method is added by the active_support gem.

Sign up to request clarification or add additional context in comments.

2 Comments

For clarity I would go for empty() (like empty? in Ruby). Slightly less dubious IMHO.
@Cimm I think both are methods in Ruby's Array class, and both are common from what I've seen.
6

Unfortunately, there isn't. The best way to do it is by comparing its length.

Comments

0

I think using in works as well.

arr = [1, 2, 3, 4, 5]
a = 1
if a in arr
  console.log 'present'
else
  console.log 'not present'

Output
$ present

1 Comment

I don't think you understood the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.