我知道此问题曾在here之前提出,但答案并不令人满意。在以下代码段的上下文中:
class MyClass
Member = Struct.new(:name)
def initialize
@members = []
end
def <<(name)
@members << Member.new(name)
end
end
如何调用或使用方法<<
?它在做什么?
答案 0 :(得分:2)
在 file:///android_asset/www/js/cordova.js Failed to load resource: net::ERR_FILE_NOT_FOUND
app.js:8 Route change!!!
app.js:8 Route change!!! /home
file:///android_asset/www/%7B%7Bn.imgurl%7D%7D Failed to load resource: net::ERR_FILE_NOT_FOUND
file:///android_asset/www/%7B%7Bt.imgurl%7D%7D Failed to load resource: net::ERR_FILE_NOT_FOUND
ionic.bundle.min.js:22 'Touch.webkitRadiusX' is deprecated and will be removed in M47, around November 2015. Please use 'Touch.radiusX' instead.
ionic.bundle.min.js:22 'Touch.webkitRadiusY' is deprecated and will be removed in M47, around November 2015. Please use 'Touch.radiusY' instead.
ionic.bundle.min.js:22 'Touch.webkitRotationAngle' is deprecated and will be removed in M47, around November 2015. Please use 'Touch.rotationAngle' instead.
ionic.bundle.min.js:22 'Touch.webkitForce' is deprecated and will be removed in M47, around November 2015. Please use 'Touch.force' instead.
index.html
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<!-- your app's css -->
<link href="css/style.css" rel="stylesheet">
<link href="css/tabSlideBox.css" rel="stylesheet">
<!-- ionic/angularjs scripts -->
<!--<script src="http://code.ionicframework.com/1.0.0-rc.4/js/ionic.bundle.min.js"></script> -->
<!--<script src="lib/ionic/js/ionic.bundle.min.js"></script> -->
<script src="lib/ionic/js/ionic.bundle.min.js"></script>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/cordova.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/tabSlideBox.js"></script>
的课程定义中:
MyClass
是一个等于Member
类的实例的类。Struct
将实例变量mc = MyClass.new
初始化为空数组。@members
与mc << "Bob"
相同,会导致结构mc.<<("Bob")
附加到数组Member.new("Bob")
。您在方法定义中使用Array#<<来定义@members
(因为MyClass#<<
是一个数组)。 @members
是通过在mc << "Bob"
的参数(mc.<<("Bob")
)周围删除可选括号并添加一茶匙"syntactic sugar"从<<
获得的,允许您用一个或多个空格替换第一个句号。它类似于"Bob"
,实际上是2 + 4
。 (试试吧。)
答案 1 :(得分:1)
你可以像这样使用它:
mc = MyClass.new
mc << 'George Clooney'
答案 2 :(得分:1)
实际上它是一种方法,我们将其用作operator
。所以在你的问题中
def <<(name)
@members << Member.new(name)
end
第一行def <<(name)
是类的方法重载,也称为猴子补丁。
第二行@members << Member.new(name)
类似于2 + 4,因为 Cary 表示。