0

In Python, there is a built-in method called __getitem__, which you can add to your classes to make a custom implementation of getting an item. For example:

class containerlist (object):

  def __init__(self, *args):
      self.container = [x for x in args]

  def __getitem__(self, i):
      return self.container[i]

In Ruby, is there an equivalent for this or other Python built-ins like __len__ or __contains__?

sawa
  • 165,429
  • 45
  • 277
  • 381
Josh Weinstein
  • 2,788
  • 2
  • 21
  • 38

3 Answers3

3

In Ruby, you access items using [], the method is called, well, [].

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • In the case of Hash and Array, where this convention is also used for other things to keep the interface feeling familiar. – tadman Sep 14 '15 at 21:16
3

Just to illustrate @Jörg W Mittag

class Containerlist
  def initialize( *args)
    @container = args
  end

  def [](i)
    @container[i]
  end
end

cl = Containerlist.new(3,4,5) #new creates a new obj and calls initialize 
p cl[1] #interpreted as cl.[](1) # => 4

About __len__ : apparently, Python interprets len(a_list) as a_list.__len__, to accommodate beginning users. Ruby prefers size and/or length and does no such thing - it's just a_list.size . So:

class Containerlist
  def size
    @container.size
  end
end
p cl.size # => 3
Community
  • 1
  • 1
steenslag
  • 79,051
  • 16
  • 138
  • 171
1

length of an array (also hashes) in ruby can written in (at least i know) two ways. calling length or count methods for an object. for string onjects you can use length method

irb(main):001:0> x = "some string"
=> "some string"
irb(main):002:0> x.class
=> String
irb(main):003:0> x.length
=> 11
irb(main):005:0> y = (1..9).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
irb(main):006:0> y.length
=> 9
irb(main):007:0> y.count
=> 9
irb(main):008:0> 

__contains__ equivalent in ruby may be include? method. actually it's more likely to in keyword.

irb(main):008:0> x.include?('s')
=> true
irb(main):009:0> y.include?('2')
=> false
irb(main):010:0> y.include?(2)
=> true

find_index for arrays and index for string may be helpful.

irb(main):013:0> y.find_index(3)
=> 2
irb(main):016:0> x.index('s')
=> 0
irb(main):017:0> x.index('s', 4) #the second argument is offset value. 
=> 5

I am not an experienced rubyist but hope these would be helpful for first steps. Also hope, not to mislead you on your ruby path :)

marmeladze
  • 6,468
  • 3
  • 24
  • 45
  • 1
    `count` may return the correct result but it's the wrong method to call in such cases. See [The Elements of Style in Ruby #13: Length vs Size vs Count](http://batsov.com/articles/2014/02/17/the-elements-of-style-in-ruby-number-13-length-vs-size-vs-count/) – cremno Sep 14 '15 at 21:19