Are there primitive types in Ruby?

ぐ巨炮叔叔 提交于 2019-12-29 05:42:03

问题


I'm a Java developer who is just starting to learn Ruby. Does Ruby have any primitive types? I can't seem to find a list of them. If not, why?


回答1:


A core principle of Ruby is that all data should be represented as objects. Other languages such as Smalltalk follow a similar paradigm.

The benefit of this design is that it makes Ruby more elegant and easier to learn. The rules applying to objects are consistently applied to all of Ruby.

For instance, when beginners are first learning Java, the difference between the primitive type int and the wrapper class Integer can be confusing. This confusion is exacerbated by the sometimes confusing implicit conversions between the two via autoboxing.

So why would languages like Java or C# bother with primitive types? The answer is performance. Creating objects incurs additional overhead when compared with primitives.




回答2:


There are no primitive data types in Ruby. Every value is an object, even literals are turned into objects:

nil.class      #=> NilClass
true.class     #=> TrueClass
'foo'.class    #=> String
100.class      #=> Integer
0x1a.class     #=> Integer
0b11010.class  #=> Integer
123.4.class    #=> Float
1.234e2.class  #=> Float

This allows you to write beautiful code:

3.times do
  puts "Hello from Ruby"
end



回答3:


Quoting from About Ruby

In Ruby, everything is an object. Every bit of information and code can be given their own properties and actions.

In many languages, numbers and other primitive types are not objects. Ruby follows the influence of the Smalltalk language by giving methods and instance variables to all of its types. This eases one’s use of Ruby, since rules applying to objects apply to all of Ruby.

Java chooses to preserve some primitive types mainly for performance, but you have to admit, not every type is a class does makes Java code a little awkward sometimes. The philosophy of Ruby is to make the programmer's days easier, I think making everything an object is one way to achieve this.



来源:https://stackoverflow.com/questions/18790442/are-there-primitive-types-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!