Ruby:为什么我在使用安全导航操作符时不会得到nil

时间:2016-10-15 16:08:38

标签: ruby

我已阅读有关安全操作员的信息。我理解它的方式是,它将在一个对象上调用一个方法,但如果该对象不存在则我们得到nil。

2.3.1 :001 > 123&.to_s
 => "123" 

但是当我在一个不存在的对象上调用方法时尝试使用它时,我得到:

2.3.1 :003 > foo&.to_s
NameError: undefined local variable or method `foo' for main:Object
Did you mean?  fork
    from (irb):3
    from /Users/duncan/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>'

我做错了什么?我误解了&amp;操作

2 个答案:

答案 0 :(得分:2)

如果未定义变量,则无法正常工作。您可以使用import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) client.loop_forever() 延迟评估

示例:

Invalid protocol "MQTT" in CONNECT from ::1.
Socket read error on client (null), disconnecting.

答案 1 :(得分:1)

安全导航器操作符可以避免在NilClass对象上调用方法,但必须定义接收器。一个无意义但有用的例子

a = [-3, -2, -1]
a.find_index(-3).zero? # true
a.find_index(5)&.zero? # nil
a.find_index(5).zero? # NoMethodError: undefined method `zero?' for nil:NilClass

to_s是一个糟糕的例子,因为nil.to_s是一个空字符串。让我们使用split

"asd-lol".split("-") # ["asd", "lol"]
nil&.split("-") # nil
nil.split("-") # NoMethodError: undefined method `split' for nil:NilClass