Reputation: 638
I am having a class G and my custom function func which i expect to take a block like this:
class G
def func(&block)
return '1' unless block_given?
# More code
end
end
I think that now when i do
G g = new G
g.func {|t| t}
block_given? should return true but its returning false
I hve tried following variants as well to no resort
g.func do |t|
end
Any help would be appreciated.
Upvotes: 2
Views: 352
Reputation: 17629
It's working fine if you correct some minor syntax errors. Note that there is no type declaration for ruby variables and object instantiation is done through an instance method of class Class
instead with keyword (like in Java):
class G
def func(&block)
return '1' unless block_given?
block.call
end
end
g = G.new
g.func { puts 'block was called' }
g.func
# Output:
# irb(main):046:0>g.func { puts 'block was called' }
# block was called
# => nil
# irb(main):047:0>g.func
# => "1"
Upvotes: 4
Reputation: 160181
(Adding my output, although Matt beat me to it.)
> class G
> def func(&block)
> return '1' unless block_given?
> # More code
> end
> end
=> nil
> g = G.new
=> #<G:0x856e444>
> g.func { |t| puts "hi" }
=> nil
> g.func
=> "1"
Upvotes: 0