Question

I'm struggling with the following code:

  • I want a method to check if a string has content or not.
has_content  = -> (a) { a!=nil && a.strip != ''}

c = ' '

has_content.call(c)
=> false
c.has_content
=> true

Why is the response different? Clearly I am lacking some Proc/lambdas knowledge.

Was it helpful?

Solution

I believe there is something missing in that code that is causing such behavior.

has_content is not defined for String, so unless you defined it before, it should raise an error

1.9.3p429 :002 > ''.has_content
NoMethodError: undefined method `has_content' for "":String
    from (irb):2
    from /Users/weppos/.rvm/rubies/ruby-1.9.3-p429/bin/irb:12:in `<main>'

As a side note, here's an alternative version of your code

has_content = ->(a) { !a.to_s.strip.empty? }

And here's an example

has_content.(nil)
# => false
has_content.('')
# => false
has_content.(' ')
# => false
has_content.('hello')
# => true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top