i don't know:&:empty?

P

Pen Ttt

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.
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

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.
: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
 

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,156
Messages
2,570,878
Members
47,413
Latest member
KeiraLight

Latest Threads

Top