I don't know:&:empty?

there is one commade:
‘[“ffgh”]78’.split(/[|]/).reject(&:empty?)
i can get two character: “ffgh” 78
but i don’t know what is the meaning of :
&:empty?
1\what is :
2\what is &:
think you for advance.

On Wed, Apr 14, 2010 at 12:18 AM, Pen T. [email protected] wrote:

:empty? is a symbol, & converts it to a proc. This is the same as saying
‘[“ffgh”]78’.split(/[|]/).reject { |str| str.empty? }

It’s purpose seems to be to remove the empty string from splitting on
the
first character (that first bracket).

p ‘[“ffgh”]78’.split(/[|]/)
p ‘[“ffgh”]78’.split(/[|]/).reject { |str| str.empty? }
p ‘[“ffgh”]78’.split(/[|]/).reject(&:empty?)

To better illustrate, lets implement something similar. Here is an
example,
where we do the same thing with a String as you do with the Symbol. (It
is a
hypothetical implementation, I don’t know how Ruby actually has it
implemented.)

puts RUBY_VERSION # for me: 1.9.1

counts = %w(first second)
begin
puts “#{counts.shift} time trying &‘empty?’”
p ‘[“ffgh”]78’.split(/[|]/).reject(&‘empty?’)
rescue
puts “rescued because String doesn’t have a to_proc method”
class String
def to_proc
lambda { |obj| obj.send self }
end
end
puts “If this was successful, then you should see the same results for
&‘empty?’ as &:empty?”
retry
end

Pen T. wrote:

1\what is :

Identifies the start of a symbol literal. That is, :empty? is a symbol
(in this case, being used as the name of a method)

2\what is &:

http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs