不传递参数调用方法

calling method without passing argument

这是我的代码

require 'rubygems'
require 'net/ldap'

class LdapUser
    def create_connection
       ldap = Net::LDAP.new
       ldap.host = 'localhost'
       ldap.port = 389
       puts "****** Conncection result ********"
       puts ldap.get_operation_result 
       return ldap
   end

  # only admin can authenticate
  def authenticate(ldap)
       ldap.authenticate "cn=admin,dc=example,dc=com",'123'  
  end
user = LdapUser.new
ldap=user.create_connection
user.authenticate(ldap)

我想用对象调用 authenticate 而不传递 ldap 作为参数。

有什么办法吗?有没有什么方法可以让代码更高效?

你可以这样做:

class LdapUser
  def ldap
    return @ldap if @ldap
    create_connection
  end

  # only admin can authenticate
  def authenticate
    ldap.authenticate "cn=admin,dc=example,dc=com",'123'  
  end

  private

  def create_connection
    @ldap = Net::LDAP.new
    @ldap.host = 'localhost'
    @ldap.port = 389
    puts "****** Conncection result ********"
    puts @ldap.get_operation_result 
    @ldap
  end
end

user = LdapUser.new
user.authenticate