ruby에서 []= 메소드 오버라이딩 하기

lazylady의 이미지

Programming Ruby에 보면 [] 요 연산자는 사실 Array의 메소드이고 오버라이딩도 가능하다라고 되어있습니다. []= 요 녀석도 오버라이딩이 가능할 것으로 아는데.. 잘 되지 않더군요. 예를 들어..

class MyArray < Array
alias oldArraySetter []=
def []= (i,o)
self.oldArraySetter(i,o)
puts "merong"
end
end

a = MyArray.new
a[0] = "asdf"

요런식으로 하면 작동하질 않습니다.
사실 매개변수가 []= (i,o) 이런식으로 되는 건지도 잘 모르겠고..

잘 아시는 분께 도움 요청합니다.
[/url]

nohmad의 이미지

lazylady wrote:
Programming Ruby에 보면 [] 요 연산자는 사실 Array의 메소드이고 오버라이딩도 가능하다라고 되어있습니다. []= 요 녀석도 오버라이딩이 가능할 것으로 아는데.. 잘 되지 않더군요. 예를 들어..
class MyArray < Array
alias oldArraySetter []=
def []= (i,o)
self.oldArraySetter(i,o)
puts "merong"
end
end

a = MyArray.new
a[0] = "asdf"

요런식으로 하면 작동하질 않습니다.
사실 매개변수가 []= (i,o) 이런식으로 되는 건지도 잘 모르겠고..

잘 아시는 분께 도움 요청합니다.
[/url]

puts "merong" 이 라인을 없애거나 위로 올리면 됩니다.

[]= 메쏘드는 내부 배열에 들어갈 값을 반환해야 합니다. lazyday님의 구현에서는 puts "merong"으로 끝나기 때문에 nil이 반환되고 그래서 원하는대로 동작하지 않은 것입니다.

lazylady의 이미지

그렇군요. 고맙습니다.
하다보니 모르는 것이 또 나와서 여쭤보겠습니다.

class MyArray < Array
alias oldArraySetter []=
def []= (i,o)
self.oldArraySetter(o,i)
i
end
end

a = MyArray.new
=>[]
a["asdf"] = 0
=>0
a
=>["asdf"]

a["asdf"] = 0의 리턴값이 "asdf"가 나오게 하고 싶은데 잘 되지 않는군요.
i 부분을 return i로 바꾸어도 마찬가지입니다.

Quote:
[]= 메쏘드는 내부 배열에 들어갈 값을 반환해야 합니다.
라고 하셨는데 그 말은 리턴값은 오버라이드할 수 없다는 얘긴가요?

ps. 의외로 구글은 특수문자를 검색할 수 없더군요. []=요걸 검색어로 할 수 없어서 애먹고 있습니다. :(

건축과 다니면서 프로그램 공부하는 이상한 사람;;

nohmad의 이미지

lazylady wrote:
그렇군요. 고맙습니다.
하다보니 모르는 것이 또 나와서 여쭤보겠습니다.

class MyArray < Array
alias oldArraySetter []=
def []= (i,o)
self.oldArraySetter(o,i)
i
end
end

a = MyArray.new
=>[]
a["asdf"] = 0
=>0
a
=>["asdf"]

a["asdf"] = 0의 리턴값이 "asdf"가 나오게 하고 싶은데 잘 되지 않는군요.
i 부분을 return i로 바꾸어도 마찬가지입니다.

Array는 순차적으로 증가하는 배열입니다. 임의의 키를 인덱스로 사용하려면, Hash를 상속해야 합니다. Array#[]=과 Hash#[]=의 차이를 생각해보세요.

Quote:
Quote:
[]= 메쏘드는 내부 배열에 들어갈 값을 반환해야 합니다.
라고 하셨는데 그 말은 리턴값은 오버라이드할 수 없다는 얘긴가요?

리턴값을 오버라이드할 수 없다는 게 아니고, []= 메쏘드가 내부 배열의 인덱스에 값을 세팅하는 것이므로 세팅할 값을 반환하도록 구현해야 한다는 것입니다.

Quote:
ps. 의외로 구글은 특수문자를 검색할 수 없더군요. []=요걸 검색어로 할 수 없어서 애먹고 있습니다. :(

http://raa.ruby-lang.org/gonzui/search?q=%5B%5D%3D&fm=all

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.